Java Reference
In-Depth Information
What if we could insist at compile time that only a certain set of constant
values be accepted? The new enumerated type feature of J2SE 5.0 does just that
and much more. Before explaining enumerated types, let's see how we might use
constants in J2SE 1.4 and below. Consider a class that accepts one of the four
seasons and returns the average temperature of that season. We might implement
such as class as follows:
public class FourSeasons
{
public static final int SPRING = 1;
public static final int FALL = 2;
public static final int SUMMER = 3;
public static final int WINTER = 4;
public float getAverageTemp (int season) {
switch (season) {
case SPRING:
return calculateSpringAverageTemp ();
case FALL:
return calculateFallAverageTemp ();
} ...
}
} // class FourSeasons
A user of this class could call it like this:
FourSeasons s4 = new FourSeasons ();
float average - temp = s4.getAverageTemp (FourSeasons.SPRING);
But there is no way to prevent a user from calling
s4.getAverageTemp (5);
resulting in unpredicatable behavior.
Using enums we can catch such errors at compile time. For this example, we
can define
public enum Season {SPRING, SUMMER, FALL, WINTER}
and then implement a method
public float getAverageTemp (Season s) {
...
}
Here the method parameter is the enum type Season , and the compiler catches
any attempt to call getAverageTemp() with any parameter other than one of
the constant names defined in the enum declaration. Note that the enum is like a
Search WWH ::




Custom Search