简体   繁体   中英

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

This is the sample 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);
    }
}

Which will print:

null
A

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

AA is a static variable. It's a bad idea, but authorized, to access static variable of a class using a variable referring to an instance of that class, even if it's null. That's not limited to enums:

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

runs fine. But it should really be written as

System.out.println(Integer.MAX_VALUE);

Enum constants are essentially static members, so they obey the exact same rules as static members.

The reason it works is exactly the reason why ((System) null).out will not cause an NPE, because its turned into a static member access which does not use the null in any way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM