Java Reference
In-Depth Information
necessary because the
for
could have been written as shown here, eliminating the need for
the
allTransports
variable:
Now, notice how the value corresponding to the name
AIRPLANE
was obtained by
calling
valueOf( )
:
As explained,
valueOf( )
returns the enumeration value associated with the name of the
constant represented as a string.
Constructors, Methods, Instance Variables, and Enumerations
It is important to understand that each enumeration constant is an object of its enumeration
type. Thus, an enumeration can define constructors, add methods, and have instance vari-
ables. When you define a constructor for an
enum
, the constructor is called when each
enumeration constant is created. Each enumeration constant can call any method defined
by the enumeration. Each enumeration constant has its own copy of any instance variables
defined by the enumeration. The following version of
Transport
illustrates the use of a
constructor, an instance variable, and a method. It gives each type of transportation a typ-
ical speed.