Jer*_*ell 3 java static-methods jvm
如果我有以下内容:
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
}
}
Run Code Online (Sandbox Code Playgroud)
使用实例调用foo()可能会出现任何问题吗?JVM是否将第一次调用foo()完全视为静态方法,还是存在一些技术细微之处?
通过从实例调用静态方法很容易引入细微的逻辑错误.例如,这不符合您的想法:
Thread t = new Thread(...);
t.sleep(1000);
Run Code Online (Sandbox Code Playgroud)
sleep
是一个静态方法,它暂停当前正在执行的线程,而不是线程实例.