I am trying to figure out how to use enum values in a switch as cases. I am a little confused as I thought I had to prefix or qualify the enum value with the enum type. Here is an example I found from Joshua Bloch in 2003 (
http://java.sun.com/features/2003/05/bloch_qa.html) which is rather old so I didn't necessarily expect it to work as the spec was finalized, but since I couldn't get my own code to work, I figured I would try this as it is what I thought I needed to do.
public enum Coin {
penny(1), nickel(5), dime(10), quarter(25);
Coin(int value) { this.value = value; }
private final int value;
public int value() { return value; }
}
public class CoinTest {
public static void main(
String[] args) {
for (Coin c : Coin.VALUES)
System.out.println(c + ": \t"
+ c.value() +"� \t" + color(c));
}
private enum CoinColor { copper, nickel, silver }
private static CoinColor color(Coin c) {
switch(c) {
case Coin.penny: return CoinColor.copper;
case Coin.nickel: return CoinColor.nickel;
case Coin.dime:
case Coin.quarter: return CoinColor.silver;
default: throw new AssertionError("Unknown coin: " + c);
}
}
}
But this does not work. The compiler throws these errors for the syntax for each case statement:
CoinTest.java:11: an enum switch case label must be the unqualified name of an enumeration constant
case Coin.nickel: return CoinColor.nickel;
^
CoinTest.java:11: duplicate case label
case Coin.nickel: return CoinColor.nickel;
^
If I remove the qualifier/prefix(i.e. Coin), then the code compiles and runs. Well, almost, VALUES needs to be changed to values() in he main method.
So, I am a little confused. Why does the switch get to buck the trend of having to qualify the enum value with the enum type? Are there other instances in which this occurs? Is this a case of
Java not being consistant or is it that switches are smart? In other words, once you use a variable reference to be switched on, the switch knows the type and only allows values of that type in the case statements. I didn't expect this since it seems everywhere else I use enums in my code, I have to do the full qualification. It made me think that the values were static, but I tested that and that is not the case either.
Any comments?
Dan