staticJava中的成员(static字段或static方法)与其各自的类相关联,而不是与此类的对象相关联.以下代码尝试访问null引用上的静态字段.
public class Main
{
private static final int value = 10;
public Main getNull()
{
return null;
}
public static void main(String[] args)
{
Main main=new Main();
System.out.println("value = "+main.getNull().value);
}
}
Run Code Online (Sandbox Code Playgroud)
虽然main.getNull()返回null,但它可以工作和显示value = 10.这段代码是如何工作的?
我用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,但上面的程序没有?为什么是这样?我不正确地理解某事吗?
我指着一些技巧并遇到了这个.在以下代码中:
public class TestClass1 {
static int a = 10;
public static void main(String ar[]){
TestClass1 t1 = null ;
System.out.println(t1.a); // At this line
}
}
Run Code Online (Sandbox Code Playgroud)
t1对象是null.为什么这段代码不抛NullPointerException?
我知道这不是访问static变量的正确方法,但问题是关于NullPointerException.