First I'll state that I'm much more familiar with enums in C# and it seems like enums in java is a quite mess.
As you can see, I'm trying to use a switch statement @ enums in my next example but I always get an error no matter what I'm doing.
The error I receive is:
The qualified case label
SomeClass.AnotherClass.MyEnum.VALUE_A
must be replaced with the unqualified enum constantVALUE_A
The thing is I quite understand the error but I can't just write the VALUE_A since the enum is located in another sub-class. Is there a way to solve this problem? And why is it happening in Java?
//Main Class
public class SomeClass {
//Sub-Class
public static class AnotherClass {
public enum MyEnum {
VALUE_A, VALUE_B
}
public MyEnum myEnum;
}
public void someMethod() {
MyEnum enumExample //...
switch (enumExample) {
case AnotherClass.MyEnum.VALUE_A: { <-- error on this line
//..
break;
}
}
}
}
We can use also use Enum keyword with Switch statement. We can use Enum in Switch case statement in Java like int primitive.
Yes, You can use Enum in Switch case statement in Java like int primitive. If you are familiar with enum int pattern, where integers represent enum values prior to Java 5 then you already knows how to use the Switch case with Enum.
We've learned that we can't create a subclass of an existing enum. However, an interface is extensible. Therefore, we can emulate extensible enums by implementing an interface.
Change it to this:
switch (enumExample) {
case VALUE_A: {
//..
break;
}
}
The clue is in the error. You don't need to qualify case
labels with the enum type, just its value.
Wrong:
case AnotherClass.MyEnum.VALUE_A
Right:
case VALUE_A:
Java infers automatically the type of the elements in case
, so the labels must be unqualified.
int i;
switch(i) {
case 5: // <- integer is expected
}
MyEnum e;
switch (e) {
case VALUE_A: // <- an element of the enumeration is expected
}
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