Accessing a static field with a NULL object in Java

前端 未结 3 570
独厮守ぢ
独厮守ぢ 2020-12-11 02:52

The following simple code snippet is working fine and is accessing a static field with a null object.

final class TestNull
{
    public static int field=100;         


        
3条回答
  •  有刺的猬
    2020-12-11 03:45

    Static variables are shared among every object of a class. So while the actual object reference you are returning is null (In C++: TestNull* temp = null;), you have an object of type TestNull which Java can use to find static values of that class.

    Remember in Java objects are really pointers. Pointers have a type. From that type Java can discern certain information, even if its pointing to null.

提交回复
热议问题