I am having some small doubts regarding Enums
. I have the following confusions :-
- What is the use of
static
methods inEnums
? Mostly we useEnums
for declaring constants. What is the use of this feature? - I see, an
Enum
can implement an interface. What would be the use? I am just confused about practical life usage. Another confusion is, see the code snippet below,
enum Position { FIRST, SECOND, THIRD; public static void main(String[] args) { //line 1 Position p = Position.SECOND; //line 2 switch(Position.THIRD) { //line 3 case FIRST: //line 4 System.out.println("Congrats, You are the winner");//line 5 break; //line 6 case SECOND : //line 7 System.out.println("Congrats, You are the runner");//line 8 break; //line 9 default : //line 10 System.out.println("Better luck next time"); //line 11 } } }
If use in
case
statement likePosition
. First,it gives a compile time error. I understand JLS does not allow this. Reason written is with a class format, it can't make a symbolic linkage. But reverse is true. Like in line-3, i am using theenum
itself with fully qualified name. So, my point is, what is the meaning of symbolic linkage and why line-3 is allowed also?
Note It was basically a typo mistake. My main question was, we are using syntax Position.THIRD in switch condition(which is allowed by compiler) but when we use same syntax in case, it is not allowed. Why is that?
Quote From 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.)
Here it mentions about Symbolic linkage. But when i wrote something like this in switch condition switch(Position.THIRD)
, it was allowed where as in CASE
statement it was.