Why should we write Enum.Val in Java, but only Val in the switch?

I have, say

private enum MyEnum { CONST1, CONST2 }

I need to write

private MyEnum var = MyEnum.CONST1;

But in the switch I will write

switch(var) {
case CONST1:
...
}

Why is this a difference?

+4
source share
2 answers

You do not need to write MyEnum.CONST1. You can use static import on it, and then you can reference CONST1 without MyEnum.

The design of the switch was provided as a convenience, so they made it as convenient as possible and do not require a name such as an enumeration. It also makes it more obvious that you can only use instances of one enumeration, and you cannot do things like this:

switch (val) {
case MyEnum1.VAL1:
  // ...
break;
case MyEnum2.VAL1:
  // ...
}
+5
source

You don’t have to. You can do:

import static package.MyEnum.CONST1;

private MyEnum var = CONST1;
+1
source

Source: https://habr.com/ru/post/1527126/


All Articles