C and C++ offer the enum
feature that allows for a set of named integer values to act as
constants. This helps prevent accidentally using an illegal value
where a group of predefined constant values, and nothing else, are
expected.
Java has not had such a feature before Java 5.0. We've
seen a related feature in BorderLayout's
constants NORTH, SOUTH, CENTER, etc. Those constants are simply
use final
static String declaration for each constant.
The new enumerated type feature of J2SE 5.0 allows
you to define at compile time a type that takes only a certain set
of constant values.
Consider a class that accepts one of the four seasons
and returns the average temperature of that season. In pre-J2SE5.0
code 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
();
...
} // getAverageTemp
} // class FourSeasons
A user of this class could call it with
FourSeasons
s4 = new FourSeasons ();
float average_temp = s4.getAverageTemp (Seasons4.SPRING);
But there is no way to prevent a user from calling
s4.getAverageTemp
(5);
resulting in unpredicatable behavior since the value
5 is not accounted for in the method getAverageTemp
()
With the new enum
statement, however, 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.
The compiler catches any attempt to call getAverageTemp()
with any parameter than one of the constant names defined in the
enum declaration.
So it acts just as if you tried to use a object of a type in a method
argument that doesn't match the type in the method definition.
So, essentially, enum
acts like a class definition. There is no need for a semicolon at
the end of the closing brace, as shown above for the Season
definition, though including one is not an error.
Enumerated types can do a lot more than replace constants.
One nice feature is the ability to obtain an array of all the enumerated
type values within an enum:
Season [] seasons
= Season.values ();
For more about the enumerated type, we refer you
to the online API documentation and the references listed below.
References & Web Resources
Latest update: Nov. 17, 2004
|