Java Reference
In-Depth Information
This version of
Transport
adds three things. The first is the instance variable
speed
,
which is used to hold the speed of each kind of transport. The second is the
Transport
constructor, which is passed the speed of a transport. The third is the method
getSpeed( )
,
which returns the value of
speed
.
When the variable
tp
is declared in
main( )
, the constructor for
Transport
is called once
for each constant that is specified. Notice how the arguments to the constructor are speci-
fied, by putting them inside parentheses, after each constant, as shown here:
These values are passed to the
s
parameter of
Transport( )
, which then assigns this value
to
speed
. There is something else to notice about the list of enumeration constants: it is
terminated by a semicolon. That is, the last constant,
BOAT
, is followed by a semicolon.
When an enumeration contains other members, the enumeration list must end in a semi-
colon.
Because each enumeration constant has its own copy of
speed
, you can obtain the speed
of a specified type of transport by calling
getSpeed( )
. For example, in
main( )
the speed
of an airplane is obtained by the following call:
The speed of each transport is obtained by cycling through the enumeration using a
for
loop. Because there is a copy of
speed
for 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 available only when enumerations are implemented as
classes, as Java does.
Although the preceding example contains only one constructor, an
enum
can offer two
or more overloaded forms, just as can any other class.
Ask the Expert
Q
:
Since enumerations have been added to Java, should I avoid the use of
final
variables? In other words, have enumerations rendered
final
variables obsolete?
A
:
No. Enumerations are appropriate when you are working with lists of items that must
be represented by identifiers. A
final
variable is appropriate when you have a con-
stant value, such as an array size, that will be used in many places. Thus, each has its