Art*_*jem 49 java null static nullpointerexception
我用Java编写了这个程序
public class Why {
public static void test() {
System.out.println("Passed");
}
public static void main(String[] args) {
Why NULL = null;
NULL.test();
}
}
Run Code Online (Sandbox Code Playgroud)
我读到调用一个null
对象的方法导致NullPointerException
,但上面的程序没有?为什么是这样?我不正确地理解某事吗?
pol*_*nts 80
test()
是一种static
方法.一个static
成员所属的类型,并且不需要一个实例来访问.
甲static
构件应该仅可以经由型表达访问.也就是说,您应该按如下方式编写:
Why.test(); // always invoke static method on the type it belongs to!
Run Code Online (Sandbox Code Playgroud)
Java允许您static
通过对象引用表达式访问成员,但这是非常误导的,因为这不是static
成员访问的实际语义.
Why aNull = null;
aNull.test(); // DO NOT EVER DO THIS!
// invokes Why.test(), does NOT throw NullPointerException
Run Code Online (Sandbox Code Playgroud)
static
通过对象引用表达式访问成员时,只有声明的引用类型才对.这意味着:
null
,因为不需要实例null
,那么对象的运行时类型是什么并不重要,没有动态调度!正如您所看到的,对于实例成员访问,两个点上的确切对立都是正确的.这就是为什么static
成员应该永远不要在一个"非访问static
"的方式,因为它给了什么它实际上做一个非常误导的外观.
this
至关重要!)