Java Reference
In-Depth Information
Despite their similarity to the
int
-based enumerated types found in C++ and other
languages,thisexample'senumsareclasses.Eachconstantisa
public static fi-
nal
field that represents an instance of its enum class.
Because constants are final, and because you cannot call an enum's constructors to
create more constants, you can use
==
to compare constants efficiently and (unlike
string constant comparisons) safely. For example, you can specify
c
==
Coin.NICKEL
.
Enums promote compile-time type safety by preventing you from comparing con-
stantsindifferentenums.Forexample,thecompilerwillreportanerrorwhenitencoun-
ters
Coin.PENNY == Weekday.SUNDAY
.
Thecompileralsofrownsuponpassingaconstantofthewrongenumkindtoameth-
od. For example, you cannot pass
Weekday.FRIDAY
to a method whose parameter
type is
Coin
.
Applicationsdependinguponenumsarenotbrittlebecausetheenum'sconstantsare
notcompiledintoanapplication'sclassfiles.Also,theenumprovidesa
toString()
method for returning a more useful description of a constant's value.
Becauseenumsaresouseful,Java5enhancedtheswitchstatementtosupportthem.
Listing3-61
demonstratesthisstatementswitchingononeoftheconstantsintheprevi-
ous example's
Coin
enum.
Listing 3-61.
Using the switch statement with an enum
class EnhancedSwitch
{
enum Coin { PENNY, ICKEL, DIME, QUARTER }
public static void main(String[] args)
{
Coin coin = Coin.NICKEL;
switch (coin)
{
case PENNY : System.out.println("1 cent"); break;
case ICKEL : System.out.println("5 cents"); break;
case
DIME
:
System.out.println("10
cents");
break;
case
QUARTER:
System.out.println("25
cents");
break;
default
: assert false;