我有以下代码
public class Test {
static String mountain = "Everest";
static Test favorite() {
System.out.print("Mount ");
return null;
}
public static void main(String[] args) {
System.out.println(favorite().mountain);
}
}
我认为它会引发一个NPE
,但它给出了Mount Everest
作为输出,任何人都可以澄清吗?
最佳答案
碰巧您可以访问对象引用上的静态成员。在这种情况下,成员根据引用的类型而不是它的值来解析。
Java Language Specification关于 static
成员的字段访问
If the field is a non-blank final field, then the result is the value of the specified class variable in the class or interface that is the type of the Primary expression.
If the field is not final, or is a blank final and the field access occurs in a constructor, then the result is a variable, namely, the specified class variable in the class that is the type of the Primary expression.
所以 Primary,即实例,并不重要。
关于java - 为什么不调用从返回 null 的静态方法链接的静态变量抛出 NPE?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20649322/