Why does the following code fail to compile, while changing the case statement to
case ENUM1: doSomeStuff();
works?
public
This is to avoid the ability to compare against different enum types. It makes sense to restrict it to one type, i.e. the type of the enum value in the switch
statement.
Update: it's actually to keep binary compatibility. Here's a cite from about halfway chapter 13.4.9 of JLS:
One reason for requiring inlining of constants is that
switch
statements require constants on eachcase
, and no two such constant values may be the same. The compiler checks for duplicate constant values in aswitch
statement at compile time; theclass
file format does not do symbolic linkage of case values.
In other words, because of the class identifier in EnumType.ENUM1
, it cannot be represented as a compiletime constant expression, while it is required by the switch
statement.
This is not really answering your question but if you have code depending on the enum value, you can also create an abstract method in your enum that gets overloaded for every value:
public enum EnumType {
ENUM1 {
@Override
public void doSomeStuff() {
// do something
}
},
ENUM2 {
@Override
public void doSomeStuff() {
// do something else
}
};
public abstract void doSomeStuff();
}
Since you're switching on an object of type EnumType
and the only possible values for it are the enum constants, there's no need to qualify those constants again in within the switch. After all, it would be illegal to have case OtherEnumType.ENUM1:
in it anyway.