Accessing a static field with a NULL object in Java

前端 未结 3 571
独厮守ぢ
独厮守ぢ 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:24

    Static fields are associated with the class not an instance of that class. Therefore you don't need an instance of an object to access the static field.

    You could also access the field by calling TestNull.field

    0 讨论(0)
  • 2020-12-11 03:36

    As opposed to regular member variables, static variables belong to the class and not to the instances of the class. The reason it works is thus simply because you don't need an instance in order to access a static field.

    In fact I'd say it would me more surprising if accessing a static field could ever throw a NullPointerException.

    If you're curious, here's the bytecode looks for your program:

    // Create TestNull object
    3: new             #3; //class TestNull
    6: dup
    7: invokespecial   #4; //Method TestNull."<init>":()V
    
    // Invoke the temp method
    10: invokevirtual   #5; //Method TestNull.temp:()LTestNull;
    
    // Discard the result of the call to temp.
    13: pop
    
    // Load the content of the static field.
    14: getstatic       #6; //Field TestNull.field:I
    

    This is described in the Java Language Specification, Section 15.11.1: Field Access Using a Primary. They even provide an example:

    The following example demonstrates that a null reference may be used to access a class (static) variable without causing an exception:

    class Test {
            static String mountain = "Chocorua";
            static Test favorite(){
                    System.out.print("Mount ");
                    return null;
            }
            public static void main(String[] args) {
                    System.out.println(favorite().mountain);
            }
    }
    

    It compiles, executes, and prints:

    Mount Chocorua

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题