Why am I able to access enum constant HOT directly in the code below:
enum SPICE_DEGREE {
MILD, MEDIUM, HOT, SUICIDE;
}
class SwitchingFun {
public static void main(String[] args) {
SPICE_DEGREE spiceDegree = SPICE_DEGREE.HOT; //Unable to access HOT directly
switch (spiceDegree) {
case HOT: //Able to access HOT directly here
System.out.println("Have fun!");
}
}
}
It's just the way the language is defined - when case labels are enum values, that means the switch
expression must be an enum of that type, so specifying the enum type everywhere would be redundant.
From JLS 14.11:
Every case label has a case constant, which is either a constant expression or the name of an enum constant.
and
If the type of the switch statement's Expression is an enum type, then every case constant associated with the switch statement must be an enum constant of that type.
See more on this question at Stackoverflow