Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: using switch statement with enum under subclass

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 constant VALUE_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;
            }
        }
    }
}
like image 605
Popokoko Avatar asked Apr 15 '12 10:04

Popokoko


People also ask

Can you use a switch statement around an enum in Java?

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

Can you use a switch statement around an enum?

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.

Can you subclass an 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.


3 Answers

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.

like image 133
darrengorman Avatar answered Oct 07 '22 20:10

darrengorman


Wrong:

case AnotherClass.MyEnum.VALUE_A

Right:

case VALUE_A:
like image 41
Akash Yellappa Avatar answered Oct 07 '22 20:10

Akash Yellappa


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
}
like image 42
Kru Avatar answered Oct 07 '22 21:10

Kru