I want to use enum-constants for switch-case-statements.
I am using following enum/class:
public enum Cons {
ONE(1),
TWO(2);
private final int val;
private Cons(final int newVal) {
val = newVal;
}
public int getVal() {
return val;
}
}
public class Main {
public static void main(String[] args) {
int test;
// some code
switch(test) {
case Cons.ONE.getVal():
// ...
break;
case Cons.TWO.getVal():
// ...
break;
default:
// ...
}
}
}
Problem:
"the case expression must be constant expression" => the values of my enum aren't constants, although the attribute private final int val
is declared as final
.
How can I use this enum for case-statements?