Java Reference
In-Depth Information
A PPENDIX I
Enumerated Types
I.1 Simple Enumerated Types
An enumerated type defines a list of enumerated values. Each value is an identifier. For exam-
ple, the following statement declares a type, named MyFavoriteColor , with values RED ,
BLUE , GREEN , and YELLOW in this order.
enum MyFavoriteColor {RED, BLUE, GREEN, YELLOW};
A value of an enumerated type is like a constant and so, by convention, is spelled with all
uppercase letters. So, the preceding declaration uses RED , not red . By convention, an enumer-
ated type is named like a class with first letter of each word capitalized.
Once a type is defined, you can declare a variable of that type:
MyFavoriteColor color;
The variable color can hold one of the values defined in the enumerated type
MyFavoriteColor or null , but nothing else. Java enumerated type is type-safe , meaning
that an attempt to assign a value other than one of the enumerated values or null will result
in a compile error.
The enumerated values can be accessed using the syntax
EnumeratedTypeName.valueName
For example, the following statement assigns enumerated value BLUE to variable color :
color = MyFavoriteColor.BLUE;
Note that you have to use the enumerated type name as a qualifier to reference a value such
as BLUE .
As with any other type, you can declare and initialize a variable in one statement:
MyFavoriteColor color = MyFavoriteColor.BLUE;
An enumerated type is treated as a special class. An enumerated type variable is therefore a
reference variable. An enumerated type is a subtype of the Object class and the Comparable
interface. Therefore, an enumerated type inherits all the methods in the Object class and the
compraeTo method in the Comparable interface. Additionally, you can use the following
methods on an enumerated object:
public String name();
Returns a name of the value for the object.
public int ordinal();
Returns the ordinal value associated with the enumerated value. The first value in
an enumerated type has an ordinal value of 0, the second has an ordinal value of 1,
the third one 3, and so on.
1283
 
 
 
Search WWH ::




Custom Search