Java Reference
In-Depth Information
Before moving on, it's necessary to make one stylistic point. The constants in
Transport
use uppercase. (Thus,
CAR
, not
car
, is used.) However, the use of uppercase is not re-
quired. In other words, there is no rule that requires enumeration constants to be in up-
percase. Because enumerations often replace
final
variables, which have traditionally used
uppercase, some programmers believe that uppercasing enumeration constants is also ap-
propriate. There are, of course, other viewpoints and styles. The examples in this topic will
use uppercase for enumeration constants, for consistency.
Java Enumerations Are Class Types
Although the preceding examples show the mechanics of creating and using an enumer-
ation, they don't show all of its capabilities. Unlike the way enumerations are implemen-
ted in some other languages,
Java implements enumerations as class types
. Although you
don't instantiate an
enum
using
new
, it otherwise acts much like other classes. The fact
that
enum
defines a class enables the Java enumeration to have powers that enumerations
in some other languages do not. For example, you can give it constructors, add instance
variables and methods, and even implement interfaces.
The values( ) and valueOf( ) Methods
All enumerations automatically have two predefined methods:
values( )
and
valueOf( )
.
Their general forms are shown here:
public static
enum-type
[ ] values( )
public static
enum-type
valueOf(String
str
)
The
values( )
method returns an array that contains a list of the enumeration constants.
The
valueOf( )
method returns the enumeration constant whose value corresponds to the
string passed in
str
. In both cases,
enum
-
type
is the type of the enumeration. For ex-
ample, in the case of the
Transport
enumeration shown earlier, the return type of
Trans-
port.valueOf("TRAIN")
is
Transport
. The value returned is
TRAIN
. The following pro-
gram demonstrates the
values( )
and
valueOf( )
methods: