我用 Java 编写了这个程序
public class Why {
public static void test() {
System.out.println("Passed");
}
public static void main(String[] args) {
Why NULL = null;
NULL.test();
}
}
我读到在 null
对象上调用方法会导致 NullPointerException
,但上面的程序不会?为什么是这样?我是不是理解不正确?
最佳答案
test()
是一个 static
方法。 static
成员属于该类型,不需要实例即可访问。
static
成员应该仅通过类型表达式访问。也就是说,你应该这样写:
Why.test(); // always invoke static method on the type it belongs to!
Java 确实允许您通过对象引用表达式访问 static
成员,但是
这是非常误导,因为这不是静态
成员访问的实际语义。
Why aNull = null;
aNull.test(); // DO NOT EVER DO THIS!
// invokes Why.test(), does NOT throw NullPointerException
当通过对象引用表达式访问 static
成员时,只有引用的声明类型很重要。这意味着:
- 如果引用实际上是
null
并不重要,因为不需要实例 - 如果引用不是
null
,不管对象的运行时类型是什么,没有动态调度!!!
如您所见,在实例成员访问的两点上都完全相反。这就是为什么 static
成员应该 NEVER 以“非static
”的方式访问,因为它给人一种非常误导的外观做。
相关问题
关于java - 为什么在空引用上调用(静态)方法不会抛出 NullPointerException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3293353/