Java Reference
In-Depth Information
own use. The advantage of enumerations is that final variables don't have to be
pressed into service for a job for which they are not ideally suited.
Two Important Restrictions
There are two restrictions that apply to enumerations. First, an enumeration can't inherit
another class. Second, an enum cannot be a superclass. This means that an enum can't be
extended. Otherwise, enum acts much like any other class type. The key is to remember
that each of the enumeration constants is an object of the class in which it is defined.
Enumerations Inherit Enum
Although you can't inherit a superclass when declaring an enum , all enumerations auto-
matically inherit one: java.lang.Enum . This class defines several methods that are avail-
able for use by all enumerations. Most often, you won't need to use these methods, but
there are two that you may occasionally employ: ordinal( ) and compareTo( ) .
The ordinal( ) method obtains a value that indicates an enumeration constant's position
in the list of constants. This is called its ordinal value . The ordinal( ) method is shown
here:
final int ordinal( )
It returns the ordinal value of the invoking constant. Ordinal values begin at zero. Thus,
in the Transport enumeration, CAR has an ordinal value of zero, TRUCK has an ordinal
value of 1, AIRPLANE has an ordinal value of 2, and so on.
You can compare the ordinal value of two constants of the same enumeration by using
the compareTo( ) method. It has this general form:
final int compareTo( enum-type e )
Here, enum-type is the type of the enumeration and e is the constant being compared to the
invoking constant. Remember, both the invoking constant and e must be of the same enu-
meration. If the invoking constant has an ordinal value less than e 's, then compareTo( )
returns a negative value. If the two ordinal values are the same, then zero is returned. If the
invoking constant has an ordinal value greater than e 's, then a positive value is returned.
The following program demonstrates ordinal( ) and compareTo( ) :
Search WWH ::




Custom Search