The identifiersJonathan,GoldenDel, and so on, are calledenumeration constants. Each is
implicitly declared as a public, static final member ofApple. Furthermore, their type is the
type of the enumeration inwhich they are declared, which isApplein this case. Thus,
in the language of Java, these constants are calledself-typed,in which “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 anenumusingnew.
Instead, you declare and use an enumeration variable in much the same way as you do one
of the primitive types. For example, this declaresapas a variable of enumeration typeApple:
Apple ap;
Becauseapis of typeApple, the only values that it can be assigned (or can contain) are those
defined by the enumeration. For example, this assignsapthe valueRedDel:
ap = Apple.RedDel;
Notice that the symbolRedDelis preceded byApple.
Two enumeration constants can be compared for equality by using the = = relational
operator. For example, this statement compares the value inapwith theGoldenDelconstant:
if(ap == Apple.GoldenDel) // ...
An enumeration value can also be used to control aswitchstatement. Of course, all
of thecasestatements must use constants from the sameenumas that used by theswitch
expression. For example, thisswitchis perfectly valid:
// Use an enum to control a switch statement.
switch(ap) {
case Jonathan:
// ...
case Winesap:
// ...
Notice that in thecasestatements, the names of the enumeration constants are used without
being qualified by their enumeration type name. That is,Winesap, notApple.Winesap, is used.
This is because the type of the enumeration in theswitchexpression has already implicitly
specified theenumtype of thecaseconstants. There is no need to qualify the constants in
thecasestatements with theirenumtype name. In fact, attempting to do so will cause a
compilation error.
When an enumeration constant is displayed, such as in aprintln( )statement, its name
is output. For example, given this statement:
System.out.println(Apple.Winesap);
the nameWinesapis displayed.
The following program puts together all of the pieces and demonstrates theApple
enumeration:
256 Part I: The Java Language