The identifiers Jonathan, GoldenDel, and so on, are called enumeration constants. Each is
implicitly declared as a public, static final member of Apple. Furthermore, their type is the
type of the enumeration in which they are declared, which is Apple in this case. Thus,
in the language of Java, these constants are called self-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 an enum using new.
Instead, you declare and use an enumeration variable in much the same way as you do one
of the primitive types. For example, this declares ap as a variable of enumeration type Apple:
Apple ap;
Because ap is of type Apple, the only values that it can be assigned (or can contain) are those
defined by the enumeration. For example, this assigns ap the value RedDel:
ap = Apple.RedDel;
Notice that the symbol RedDel is preceded by Apple.
Two enumeration constants can be compared for equality by using the = = relational
operator. For example, this statement compares the value in ap with the GoldenDel constant:
if(ap == Apple.GoldenDel) // ...
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
expression. For example, this switch is perfectly valid:
// Use an enum to control a switch statement.
switch(ap) {
case Jonathan:
// ...
case Winesap:
// ...
Notice that in the case statements, the names of the enumeration constants are used without
being qualified by their enumeration type name. That is, Winesap, not Apple.Winesap, is used.
This is because the type of the enumeration in the switch expression has already implicitly
specified the enum type of the case constants. There is no need to qualify the constants in
the case statements with their enum type name. In fact, attempting to do so will cause a
compilation error.
When an enumeration constant is displayed, such as in a println( ) statement, its name
is output. For example, given this statement:
System.out.println(Apple.Winesap);
the name Winesap is displayed.
The following program puts together all of the pieces and demonstrates the Apple
enumeration:
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home