Java Reference
In-Depth Information
final static int FRIDAY = 5;
final static int SATURDAY = 6;
}
Listing3-59
'
sand
3-60
'sapproachtorepresentinganenumeratedtypeisproblematic,
wherethebiggestproblemisthelackofcompile-timetypesafety.Forexample,youcan
pass a coin to a method that requires a weekday and the compiler will not complain.
You can also compare coins to weekdays, as in
Coin.NICKEL == Week-
day.MONDAY
, and specify even more meaningless expressions, such as
Coin.DIME+Weekday.FRIDAY-1/Coin.QUARTER
.Thecompilerdoesnotcom-
plain because it only sees
int
s.
Applications thatdependuponenumerated typesarebrittle. Because thetype'scon-
stantsarecompiledintoanapplication'sclassfiles,changingaconstant's
int
valuere-
quires you to recompile dependent applications or risk them behaving erratically.
Another problem with enumerated types is that
int
constants cannot be translated
intomeaningfulstringdescriptions.Forexample,whatdoes4meanwhendebugginga
faulty application? Being able to see
THURSDAY
instead of
4
would be more helpful.
Note
You could circumvent the previous problem by using
String
constants.
For example, you might specify
final static String THURSDAY =
"THURSDAY";
. Although the constant value is more meaningful,
String
-based
constants can impact performance because you cannot use
==
to efficiently compare
String
-basedconstantsincludehard-codingtheconstant'svalue(
"THURSDAY"
)in-
stead of the constant's name (
THURSDAY
) into source code, which makes it difficult
to change the constant's value at a later time; and misspelling a hard-coded constant
(
"THURZDAY"
), which compiles correctly but is problematic at runtime.
The Enum Alternative
Java5introducedenumsasabetteralternativetotraditionalenumeratedtypes.Anenum
isanenumeratedtypethatisexpressedviareservedword
enum
.Thefollowingexample
enum Coin { PENNY, ICKEL, DIME, QUARTER }
enum
Weekday
{
SUNDAY,
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY, FRIDAY, SATURDAY }