Why not a NullPointerException while accessing sta

2019-01-26 11:59发布

Here in following code we are getting value of i on a null reference, though a NPE is not there.

public class Test {
    static int i = 10;

    Test getTest() {
        return null;    
    }

    public static void main(String args[]) {
        Test t = new Test();
        System.out.println(t.getTest());  
        System.out.println(t.getTest().i);
    }
}

output

null
10

8条回答
混吃等死
2楼-- · 2019-01-26 12:33
 Test t = new Test(); // initialize t

Here t isn't null as it has been initialized. Thus, you do not get a NullPointerException.

In next case where you expected a NullPointerException since t.getTest() returned null,

t.getTest().i;

i is a static variable and you do not need to an instance to access static variables, you can just access them directly. Thus, you do not get NullPointerException here too.

And moreover,

System.out.println(i); // is an another way to access static i
查看更多
放荡不羁爱自由
3楼-- · 2019-01-26 12:34

i being a static variable, no instance is needed to get its value.

查看更多
登录 后发表回答