Static method in Java can be accessed using object instance

39,291

Solution 1

A benefit of this is that it allows you to take an instance method and turn it into a static method without having to modify any existing code (other than the class) and thus allowing for backwards compatibility. I've found this useful as many times I've come across utility methods that can be made static - I can just add the static modifier and continue on my way.

Solution 2

Semantically identical. The compiler is smart enough to know what you mean (that is access the static method through the class). IDEs will give you a warning telling you it's bad manners :)

Look at this question for more details. As they say it can be misleading and that's why IDEs will give you a warning.

Solution 3

It's allowed by spec, but it's not recomended. Further more IDE's like Eclipse mark access to a static method on an object instance with an warning.

Solution 4

while it's bad, there is no compelling reason to forbid it either.

o.f();

so we need to find a method named f in the scope of o. One could argue that a static f is of course also in the scope of o, even though f is actually defined for a larger scope (o's class)

Share:
39,291
Rengasami Ramanujam
Author by

Rengasami Ramanujam

I am a person who is a developer using Java and willing to become a Java developer. I want to learn Java along with its beauty. Most of the people in corporate world now trying to say that they are JAVA professional just with a SCJP or with certain yrs of experience. Really speaking unless we understand the beauty of Java we can't appreciate it. I strongly beleive this!! Apart from Java I have interests on cloud computing, networks, Algorithms and Computer architecture optimization.

Updated on June 22, 2020

Comments

  • Rengasami Ramanujam
    Rengasami Ramanujam about 4 years

    In Java static methods are created to access it without any object instance. It makes some sense to me. But recently I came across one strange thing that, static method in Java can also be accessed through its object instance. This looks pretty wierd to me. Does anyone of you know why this feature is provided by Java? Whats the significance of allowing static methods getting accessed with as well as without instance?