Why does the following code fail to compile, while changing the case statement to
case ENUM1: doSomeStuff();
works?
public enum EnumType { ENUM1, ENUM2, ENUM3; void doSomeStuff() { switch(this) { case EnumType.ENUM1: doSomeStuff(); } } }
An enum is a special class that represents a group of constants. To create an enum, use the enum keyword (instead of class or interface), and separate the constants with a comma. values() method can be used to return all values present inside enum.
We can use also use Enum keyword with Switch statement. We can use Enum in Switch case statement in Java like int primitive.
Enum 's valueOf(String) Method Careful, the strings passed to valueOf are case sensitive!
4) Adding new constants on Enum in Java is easy and you can add new constants without breaking the existing code.
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.
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