为什么在null引用上调用(静态)方法不会抛出NullPointerException?

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"的方式,因为它给了什么它实际上做一个非常误导的外观.

相关问题