Helping ordinary people create extraordinary websites!

Getting Started with Enumerated Types

By Brett McLaughlin
2005-04-22

Represent Constants in a Typesafe Manner Using Java 5.0
One of the great new features in Tiger is the enumeration construct, a new type that allows you to represent specific pieces of data as constants, all in a type-safe manner. Tiger expert and frequent developerWorks contributor Brett McLaughlin explains what an enumeration is, how you can use it in your programs, and why it will allow you to dump all that old public static final code.

You already know that the two fundamental building blocks of Java code are classes and interfaces. Now Tiger has introduced one more: the enumeration. Usually referred to simply as an enum, this new type allows you to represent specific data points that accept only certain sets of pre-defined values at assignment time.

Of course, well-practiced programmers already know you can achieve this functionality with static constants, as shown in Listing 1:

Listing 1. Public static final constants

public class OldGrade {


public static final int A = 1;
public static final int B = 2;
public static final int C = 3;
public static final int D = 4;
public static final int F = 5;
public static final int INCOMPLETE = 6;
}
Note: I'd like to thank O'Reilly Media, Inc., which has permitted me to use the code sample from the "Enumerations" chapter of my book Java 1.5 Tiger: A Developer's Notebook for this article (see Resources).

You can then set up classes to take in constants like OldGrade.B, but when doing so keep in mind that such constants are Java ints, which means the method will accept any int, even if it doesn't correspond to a specific grade defined in OldGrade. Therefore, you'll need to check for upper and lower bounds, and probably include an IllegalArgumentException if an invalid value appears. Also, if another grade is eventually added (for example, OldGrade.WITHDREW_PASSING), you'll have to change the upper bound on all your code to allow for this new value.

In other words, while using classes with integer constants like this might be a passable solution, it's not a very efficient one. Fortunately, enumerations offer a better way.



Tutorial pages:

First published by IBM developerWorks


 2 Votes

You might also want to check these out:


Leave a Comment on "Getting Started with Enumerated Types"
You must be logged in to post a comment.

Link to This Tutorial Page!


GET OUR NEWSLETTERS