UserStack2255222555 UserStack2255222555 - 1 year ago 68
Java Question

JAVA: difference between Static method invocation with className and with Object of instance

I'm little confused on the calling static methods, any way i know this kind of rule

Foo.staticMethod(); //accessing static method.

for non-static method we must instantiate the class.

Foo person1 = new Foo(); //instantiating
person1.nonStaticMethod(); //accessing non-static method.

so all we know that static methods are known among the class so does not give a sens when we call it within the object reference like in Doc Oracle
its say :

Note: You can also refer to static methods with an object reference like
but this is discouraged because it does not make it clear that they are class methods.

Finally my question is as below:

public class Foo{

static int x = 10;

public static void method(){
System.out.println("ANYTHING TO SHOW !!!!");

public static void main(String[] args) {
Foo object = new Foo();

object.method(); // ANYTHING TO SHOW !!!!
Foo.method(); // ANYTHING TO SHOW !!!!

System.out.println(object.x); // Will display as result 10
System.out.println(Foo.x); //Also this will display as result 10

So why the documentation montioned that static field/method not longer with object ref while is give the same.

Note :

I know the uses of static keyword, that give smooth ref into memory which each variable declared once into the memory while is
attached to static keyword, also i know very well that static keyword
useful for hiding method from overriding when we deal with inheritance.
so these not included into my question.

Answer Source

By convention...

  • If one sees object.method(), they assume that method() is an instance method and requires an instance of Foo to be used.

  • If one sees Foo.method(), they know that method() is a static method and does not require an instance of Foo to be used.

This is a code readability issue more than a functional issue, since you demonstrate correctly that the code will work in either scenario. However, it does make understanding that code harder, since now the developer has to be wary of any other possible use of a static method in that fashion.

Remember: static methods don't require an instance for a reason. If you find yourself needing an instance for the method at all, it may be worth reconsidering its design.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download