Java The Complete Reference, Seventh Edition

(Greg DeLong) #1

260 Part I: The Java Language


// Display price of Winesap.
System.out.println("Winesap costs " +
Apple.Winesap.getPrice() +
" cents.\n");

// Display all apples and prices.
System.out.println("All apple prices:");
for(Apple a : Apple.values())
System.out.println(a + " costs " + a.getPrice() +
" cents.");
}
}

The output is shown here:

Winesap costs 15 cents.

All apple prices:
Jonathan costs 10 cents.
GoldenDel costs 9 cents.
RedDel costs 12 cents.
Winesap costs 15 cents.
Cortland costs 8 cents.

This version ofAppleadds three things. The first is the instance variableprice, which is
used to hold the price of each variety of apple. The second is theAppleconstructor, which
is passed the price of an apple. The third is the methodgetPrice( ), which returns the value
ofprice.
When the variableapis declared inmain( ), the constructor forAppleis called once for
each constant that is specified. Notice how the arguments to the constructor are specified,
by putting them inside parentheses after each constant, as shown here:

Jonathan(10), GoldenDel(9), RedDel(12), Winesap(15), Cortland(8);

These values are passed to thepparameter ofApple( ), which then assigns this value toprice.
Again, the constructor is called once for each constant.
Because each enumeration constant has its own copy ofprice, you can obtain the price of
a specified type of apple by callinggetPrice( ). For example, inmain( )the price of a Winesap
is obtained by the following call:

Apple.Winesap.getPrice()

The prices of all varieties are obtained by cycling through the enumeration using aforloop.
Because there is a copy ofpricefor each enumeration constant, the value associated with
one constant is separate and distinct from the value associated with another constant. This
is a powerful concept, which is only available when enumerations are implemented as classes,
as Java does.
Although the preceding example contains only one constructor, anenumcan offer two
or more overloaded forms, just as can any other class. For example, this version ofApple
provides a default constructor that initializes the price to –1, to indicate that no price data
is available:
Free download pdf