How can I access static variables from a null reference?

I recently looked through a page on javarevisited and found a block of code that asked readers to determine what would be the result for it ...

Although I got the result, I am not happy with the result (WHICH CAME OUT TO BE "Hello"), since I do not know how to access the static member from a null reference. What happens in the background?

public class StaticDEMO {

    private static String GREET = "Hello";

    public static void main(String[] args) {
        StaticDEMO demo = null;
        System.out.println(demo.GREET);
        // TODO code application logic here
    }
}
+4
source share
4 answers

, JVM , . demo ( a StaticDEMO), , GREET.

, ( , , , - ). , , ( , !).

, :

System.out.println(StaticDEMO.GREET);

Java: 15, 11: .

15.11.1-2.

, (),

[ ]

+12

, Java, , memeber . , . / , - . , , , , - .

+4

Static elements are stored with the class, and not with any particular instance. So it doesn't matter that the instance is null - the member from the class is still available.

+2
source

The JVM simply ignores nullit because it GREETis a class field, but demoa non-reference field Class.

StaticIt does not require an object reference to call it, so you can name it, even an object reference null.

0
source

Source: https://habr.com/ru/post/1570254/


All Articles