Koray Tugay Koray Tugay - 13 days ago 12
Java Question

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?

Answer

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);