Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

enums

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?

like image 849
Koray Tugay Avatar asked Nov 27 '16 17:11

Koray Tugay


2 Answers

A.A 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);
like image 124
JB Nizet Avatar answered Sep 29 '22 02:09

JB Nizet


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.

like image 34
Kiskae Avatar answered Sep 29 '22 01:09

Kiskae