What are the problems with using objects in Java to call static methods?

If I have the following:

class A {
  public A() { }
  public static void foo() { System.out.println("foo() called"); }
}

public class Main {
  public static void main(String [] args) {
    A a = new A();
    a.foo(); // <-- static call using an instance.
    A.foo(); // <-- static call using class
  }
}

Is there any problem with calling foo () using an instance? Does the JVM treat the first call to foo () as a static method, or are there some technical nuances?

Solution

It is easy to introduce subtle logical errors by calling static methods from instances For example, this is not what you think:

Thread t = new Thread(...);
t.sleep(1000);

Sleep is a static method that pauses the currently executing thread, not the thread instance

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>