Java Reference
In-Depth Information
The identifiers CAR , TRUCK , and so on, are called enumeration constants . Each is im-
plicitly declared as a public, static member of Transport . Furthermore, the enumeration
constants' type is the type of the enumeration in which the constants are declared, which is
Transport in this case. Thus, in the language of Java, these constants are called self-typed ,
where “self” refers to the enclosing enumeration.
Once you have defined an enumeration, you can create a variable of that type. However,
even though enumerations define a class type, you do not instantiate an enum using new .
Instead, you declare and use an enumeration variable in much the same way that you do
one of the primitive types. For example, this declares tp as a variable of enumeration type
Transport :
Because tp is of type Transport , the only values that it can be assigned are those defined
by the enumeration. For example, this assigns tp the value AIRPLANE :
Notice that the symbol AIRPLANE is qualified by Transport .
Two enumeration constants can be compared for equality by using the = = relational op-
erator. For example, this statement compares the value in tp with the TRAIN constant:
An enumeration value can also be used to control a switch statement. Of course, all of
the case statements must use constants from the same enum as that used by the switch ex-
pression. For example, this switch is perfectly valid:
Search WWH ::




Custom Search