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?
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With