-2

I have to work with a library that defines an enum like this:

public static enum LibVal {
    VAL_1,
    VAL_2,
    VAL_3;
}

I get this enum as a method argument:

public void libCallback(LibVal val){
    //.... some implementation
}

Why does Java disallow the use of switch with the LibVal enum inside the libCallback method? However, if the lib had declared its enum as non-static it would work. This is confusing as this SO-answer states, that there is really no difference...

Edit:

As bobkilla Stated: I tried LibVal.VAL_1 inside my switch, which should be allowed. I provide a code-sample which wouldn't work!

class TestClassForEnum {
    public static enum TestEnum{ ONE, TWO; }
}

class WhichUsesEnumInsideMethod{

    //completely unrelated to TestClassForEnum.TestEnum!!!
    public static final int ONE = 0x1282

    void doSomethingWithEnum(TestEnum e){
        //here I cannot switch:

        //FORBIDDEN BY JAVA
        switch (e) {
            case TestEnum.ONE:
                    //...

        }

        //Cannot USE EITHER, because ONE is a static final int inside this scope?!:
        switch (e) {
            case ONE:
                    //...

        }

 }
Community
  • 1
  • 1
Rafael T
  • 15,401
  • 15
  • 83
  • 144

3 Answers3

5

this will not work :

switch(val) {
            case LibVal.VAL_1: System.out.println("VAL_1 was chosen");
        }

this will work :

switch(val) {
            case VAL_1: System.out.println("VAL_1 was chosen");
        }
bobkilla
  • 121
  • 2
  • 9
  • oh You are right. I tried `LibVal.VAL_1` which is not working. do You know why I'm not allowed to prefix it with LibVal? – Rafael T May 13 '13 at 12:23
  • I don't know why, I just know it will not compile if you use the prefix. And for your 'ONE' problem, i think it is because ONE is a static final int in this scope. – bobkilla May 13 '13 at 12:47
  • yes of course it is. Thats Why I initially thought, that I cannot switch over an enum at all... – Rafael T May 13 '13 at 12:50
2

All enum are static by default and there is no difference. You can switch on any enum, whether you make it static or not.

See this example here http://ideone.com/n5oQoi

public class Main {
    public static enum LibVal {
        VAL_1,
        VAL_2,
        VAL_3;
    }

    public void libCallback(LibVal val){
        switch(val) {
            case VAL_1: System.out.println("VAL_1 was chosen");
        }
    }

    public static void main(String[] ignored) {
        new Main().libCallback(LibVal.VAL_1);
    }
}
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
1
// your method signature:
public void libCallback(LibVal val){
    switch (val) {
    case VAL_1: System.out.println("It"); break;
    case VAL_2: System.out.println("works"); break;
    case VAL_3: System.out.println("fine"); break;
    default:    System.out.println("here.");
    }
}
jlordo
  • 37,490
  • 6
  • 58
  • 83