[英]Why does this not cause a NullPointerException?
public class Null {
public static void greet() {
System.out.println("Hello world!");
}
public static void main(String[] args) {
((Null) null).greet();
}
}
program output: Hello world!
程序输出:
Hello world!
. 。
I thought it would throw a NullPointerException
. 我以为它会抛出一个
NullPointerException
。
Why is it happenning? 它为什么会发生?
method greet()
is static, thus it does not need an enclosing instance of Null
. 方法
greet()
是静态的,因此它不需要Null
的封闭实例。 Actually, you can [and should] invoke it as: Null.greet();
实际上,你可以[并且应该]调用它:
Null.greet();
The reason is that greet()
is a static
method. 原因是
greet()
是一个static
方法。 References to static methods via variables do not result in dereferencing the pointer. 通过变量引用静态方法不会导致取消引用指针。 The compiler should have warned you about this.
编译器应该已经警告过你。
If you remove the static
modifier then you will get the npe
如果你删除
static
修改器,那么你将得到npe
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.