I keep missing questions on enums because I can't figure out when the enum value *must* be qualified with the enum class name and when it doesn't have to be. (I.e., for enum "MyEnum", when value FOO must be referred to as MyEnum.FOO vs. when it you could just use FOO.)
I know that in a switch statement, the case labels don't have to be qualified; that makes sense since you are using an enum variable for the switch test. But I thought that was the only time, outside the enum definition.
Then I did a practice test question where an enum was imported from another package, and the enum values were used without qualification, e.g. just calling them FOO. I thought that was incorrect syntax so I chose "compilation fails" for the answer - but that was wrong!
Is there a succinct rule for knowing when to qualify? At the moment I'm just concerned with what would be legal Java syntax; personally I would always want to qualify the values to make the code clearer.
Good question! That's just the sort of thing that keeps catching me. I read the study guides and learn how things should be done, but it's not always clear whether it's *legal* to do them differently. And then I get a question on a practice exam that breaks one of those rules, and I'm not sure whether that means it won't compile, or just that it would be frowned upon.
E.g. one question that caught me more than once in the Rules Roundup was the one about whether a subclass can define a method that's final in the superclass. I may not be quoting the exact wording correctly, but even if you know that (a) you can create a method with the same signature in the subclass and (b) it won't technically be overriding the method in the superclass, it's still hard to be sure what the particular question has in mind.
But, I digress... !! I just remembered, this thread is about enums.
(Although my question about enums *is* really just an instantiation of my general trouble with distinguishing "poor coding practice" from "illegal Java code".)
b. [ September 09, 2006: Message edited by: E McKenney ]
Originally posted by Burkhard Hassel: Wasn't it must not be qualified in a case label?
You're right. In fact you can get some interesting compile errors if you do qualify it. I wrote a quick program with a switch statement, and qualified some of the case labels but not others. The ones that were qualified got errors, as you predicted, but the compiler threw in a couple of extras:
I guess when the compiler complains about the qualified enum value, it must substitute something generic there before parsing the next statement. Then when it does the same thing on the next label, that results in a "duplicate case label". Obviously I'm not giving the compiler enough to do, if it's starting to create its own errors...