What is the default value for an instance variable of type Enum in Java?

This is an example of the code I have:

enum A {
    A,
}

class TestA {
    A a;
    public static void main(String[] args) {
        final TestA testA = new TestA();
        System.out.println(testA.a);
        System.out.println(testA.a.A);
    }
}

What will print:

null
A

If the default value for an uninitialized Enum instance variable is null, how does accessing an Enum instance work?

+4
source share
2 answers

AA is a static variable. This is a bad idea, but authorized to access a static class variable using a variable that refers to an instance of this class, even if it is null. This is not limited to enumerations:

Integer i = null;
System.out.println(i.MAX_VALUE);

works fine. But it really should be written as

System.out.println(Integer.MAX_VALUE);
+7
source

, , .

, , , ((System) null).out NPE, , null.

+4

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


All Articles