Java The Complete Reference, Seventh Edition

(Greg DeLong) #1

Chapter 12: Enumerations, Autoboxing, and Annotations (Metadata) 259


Notice that this program uses a for-each styleforloop to cycle through the array of
constants obtained by callingvalues( ). For the sake of illustration, the variableallapples
was created and assigned a reference to the enumeration array. However, this step is not
necessary because theforcould have been written as shown here, eliminating the need for
theallapplesvariable:


for(Apple a : Apple.values())
System.out.println(a);


Now, notice how the value corresponding to the nameWinesapwas obtained by calling
valueOf( ).


ap = Apple.valueOf("Winesap");


As explained,valueOf( )returns the enumeration value associated with the name of the
constant represented as a string.


NOTEOTE C/C++ programmers will notice that Java makes it much easier to translate between the
human-readable form of an enumeration constant and its binary value than do these other
languages. This is a significant advantage to Java’s approach to enumerations.


Java Enumerations Are Class Types


As explained, a Java enumeration is a class type. Although you don’t instantiate anenum
usingnew, it otherwise has much the same capabilities as other classes. The fact thatenum
defines a class gives powers to the Java enumeration that enumerations in other
languages simply do not have. For example, you can give them constructors, add instance
variables and methods, and even implement interfaces.
It is important to understand that each enumeration constant is an object of its enumeration
type. Thus, when you define a constructor for anenum, the constructor is called when each
enumeration constant is created. Also, each enumeration constant has its own copy of any
instance variables defined by the enumeration. For example, consider the following version
ofApple:


// Use an enum constructor, instance variable, and method.
enum Apple {
Jonathan(10), GoldenDel(9), RedDel(12), Winesap(15), Cortland(8);


private int price; // price of each apple

// Constructor
Apple(int p) { price = p; }

int getPrice() { return price; }
}


class EnumDemo3 {
public static void main(String args[])
{
Apple ap;

Free download pdf