Elliott C. Back: Technology FTW!

Enumerated Constants in Java

Posted in Computers & Technology, Java by Elliott Back on March 3rd, 2005.

Java 1.5 introduces this great feature long present in other languages called an enumerated constant. In theory, it lets you replace ugly java code like this:

public static final int PANCAKE = 0;
public static final int ORANGES = 0;
public static final int CEREAL = 0;
public static final int MILK = 0;

With a simple one line definition:

public enum breakfast { pancake, oranges, cereal, milk };

This is good because it improves the readability and maintability of the code. Enums are also strictly more powerful than a list of integers, as they are actually a shorthand for a class, and contain methods and fields of their own. However, transitioning to using java 1.5 is not as easy as you think. I wanted to use an enum in a switch / case statement, but was having trouble. My first incorrect try was to fully qualify the enum:

switch(visited.operator){
    case BinaryExpression.Operator.and: … break;
}

This gives the following error:

The enum constant BinaryExpression.Operator.and reference cannot be qualified in a case label

Searching for tutorials online didn’t help–the only one I could find that was truly useful was this one from InformIT. I finally discovered that it inherits the context from the type of the object in the switch() statement, and that cases can simply use unqualified names. The code now becomes:

switch (visited.operator) {
    case and: … break;
}

One you get used to them, enums in Java 1.5 are great. They really should have been there all along!

This entry was posted on Thursday, March 3rd, 2005 at 5:09 pm and is tagged with cereal milk, case label, case statement, switch case, switch statement, informit, java code, java java, integers, using java, shorthand, oranges, readability, constants, nbsp, languages. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback.

Viewing 23 Comments

 

Trackbacks

(Trackback URL)

close Reblog this comment
blog comments powered by Disqus