[Java] The enum constant reference cannot be qualified in a case label of switch statement - Digizol6

Post Top Ad

Responsive Ads Here

Post Top Ad

Responsive Ads Here

Tuesday, October 19, 2010

[Java] The enum constant reference cannot be qualified in a case label of switch statement

The enum constant reference cannot be qualified in a case label is an error message you may encounter while using Java enum values against a switch statement. I assume you are aware Java allows enums to be used in switch statements other than convertible int values.

In Short

When a Java switch statement uses an enum parameter; qualified names of the enum values should not be used in case labels, but only the unqualified names; then switch statement will consider all the labels are referring to the enum type that is used as the parameter.

Why only unqualified values?

If qualified references were allowed for case labels; there would be no means to restrict the enum type used in the labels to be same as the parameter type of switch statement.

In Detail

An enum named “Status” which represent two statuses of an entity will be used in sample code.

package org.kamal.learnenum.user;

public enum Status {
REGISTERED,
TERMINATED
}

Following sample code uses “Status” enum to create a a greeting message (based on a complex logic). Look at the way the case label is written in switch statement; consider the differences in lines marked as 1 & 2.

package org.kamal.learnenum.test;

import org.kamal.learnenum.user.Status;

public class TestStatus {
public static String getMessage(Status status) {
String message;
switch (status) {
// case Status.REGISTERED: // line 1
case REGISTERED: // line 2
message = "Welcome";
break;
default:
message = "Good bye";
break;
}
return message;
}

public static void main(String[] args) {
String name = "John";
System.out.println(getMessage(Status.REGISTERED) + " " + name);
System.out.println(getMessage(Status.TERMINATED) + " " + name);
}
}

Status & TestStatus classes are in two different packaged; so to refer to a Status enum value inside TestStatus class we must use qualified name like follows.

Status status = Status.REGISTERED;

However when it comes to case labels of switch statements; enum should not be referred using qualified name. What? Are you sure? Yes; that is the truth. Only unqualified enum value must be used for case labels. The compiler will simply look at the type of the enum parameter to the switch() statement and refer to that enum class to locate the enum values.

No comments:

Post a Comment

Post Top Ad

Responsive Ads Here