J2SE 1.5: Java's Evolution Continues : Page 3

J2SE 1.5 (codename: Tiger) epitomizes Java's ongoing evolution and adaptation to the emerging needs of programmers and their applications. With features such as generics, autoboxing, and enhanced for loops, it makes Java code easier to develop and read.

by Kulvir Singh Bhogal

Mar 8, 2004

Page 3 of 4

Typesafe Enums
Tiger brings to the table a new type named enum. Using this keyword, one can define a set of valid values or states. Consequently, you can ensure type safety during compile time. For example, if you wanted to realize the concept of enumerations in the past, you might have used constants like in the following code:

public class TrafficLight
{
public static final int GREEN = 1;
public static final int RED = 0;
public static final int YELLOW = 2;
// light is green by default
private int state = GREEN;
// get the current light state
public int getState()
{
return this.state;
}
// set the current light state
// notice no protection of what the light can be set to
public void setState(int state)
{
this.state = state;
}
}

The code of the EnumExample class demonstrates how you previously had to use a helper class to represent a set of states. Notice the absence of state setting safeguards. To elaborate, your states are represented by integers, and they have no safeguard to prevent the constructor of your TrafficLight from taking an integer greater than 2 (representing yellow). You could throw in some custom Boolean logic to add restrictions, but it would be quite cumbersome to create. Also, the numbers 0, 1, and 2 can lead to errors. You could accidentally assume that 0 represents green somewhere in your code. Now that would cause some traffic nightmares, wouldn't it?

Take a look at the method newMethodologyWithEnum(). When you use the enum, you create a new enumeration and clearly define what your possible states can be. Switching between states is easier and your code does not rely on an auxiliary class anymore:

Static Imports
Tiger's static import feature eliminates the need to prefix static members of a class with class names. It's similar to the package import facility you are used to (except that you import static members from a class rather than classes from a package). The following example class juxtaposes how you had to perform things in the past and how Tiger's offerings can make your code much more abbreviated: