Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I get an Enum constant reference cannot be qualified in a case label?

Tags:

java

enums

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();         }     } } 
like image 563
Maleki Avatar asked Apr 18 '10 21:04

Maleki


People also ask

How do you declare a constant in an enum?

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.

Is enum allowed in switch case?

We can use also use Enum keyword with Switch statement. We can use Enum in Switch case statement in Java like int primitive.

Is enum value of case sensitive?

Enum 's valueOf(String) Method Careful, the strings passed to valueOf are case sensitive!

Can we add constants to enum without breaking existing code?

4) Adding new constants on Enum in Java is easy and you can add new constants without breaking the existing code.


1 Answers

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 each case, and no two such constant values may be the same. The compiler checks for duplicate constant values in a switch statement at compile time; the class 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.

like image 96
BalusC Avatar answered Sep 19 '22 07:09

BalusC