Since enums are objects, yes, they will be initialized to null if they are class/instance members. Edit (clarification): A reference to an enum, like c, will be initialized to null if it is a class or instance member.
Your confusion may stem from the misleading name given to the enum type. Just like classes, an enum is usually given a singular name, like Color in this case, not plural.
Yes, the variable c is initialized to null and never changed to any other value. However the expression c.RED doesn't actually use the variable c. It's actually equivalent to Colors.RED; I'm not sure why the designers of Java made this legal but they did.
Hi (again) Junilu.
Thanks for all the answers you provide!
Junilu Lacar wrote:Since enums are objects, yes, they will be initialized to null if they are class/instance members. Edit (clarification): A reference to an enum, like c, will be initialized to null if it is a class or instance member.
Paul Clapham wrote:Yes, the variable c is initialized to null and never changed to any other value. However the expression c.RED doesn't actually use the variable c. It's actually equivalent to Colors.RED; I'm not sure why the designers of Java made this legal but they did.
Yes, it is. You didn't mention it but that makes me suspect your code came from something which is aimed at people taking a certification exam. I wouldn't expect to find that "feature" in real code anywhere.
Java compiles an enum into something very similar to this regular class definition:
Since static members of a class can also be accessed via a variable reference, I guess it makes sense to allow access to an enum value via a variable reference. It's confusing though, as you have seen, so you should avoid doing that.
Paul Clapham wrote:Yes, it is. You didn't mention it but that makes me suspect your code came from something which is aimed at people taking a certification exam. I wouldn't expect to find that "feature" in real code anywhere.
What an eye! :)
Actually I took and "adapted" a question from a book on OCAJP I'm studied.
Paul Clapham wrote:Yes, the variable c is initialized to null and never changed to any other value. However the expression c.RED doesn't actually use the variable c. It's actually equivalent to Colors.RED; I'm not sure why the designers of Java made this legal but they did.
Color.RED is the preferable way to access static members. Then you can do away with 'c' entirely.
Junilu Lacar wrote:Since static members of a class can also be accessed via a variable reference, I guess it makes sense to allow access to an enum value via a variable reference.
Yes, I'd seen the former usage before (discussed here on the Ranch) but not the latter. But yeah, I guess they are the same thing.