paidedly
paidedly

Reputation: 1413

Why am I able to access enum constants directly as case labels of a switch statement in another class

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!");
        }
    }
}

Upvotes: 0

Views: 81

Answers (2)

Konstantin Yovkov
Konstantin Yovkov

Reputation: 62864

Java infers the type of the expression, provided in the switch statement and then allows only valid values for the resolved type to be listed in the case blocks.

It would be too verbose if we had to specify the type of the enum constant for each case.

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1502835

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.

Upvotes: 4

Related Questions