Java Reference
In-Depth Information
}
}
}
Listing3-61 demonstratesswitchingonanenum'sconstants.Thisenhancedstatement
onlyallowsyoutospecifythenameofaconstantasacaselabel.Ifyouprefixthename
with the enum, as in case Coin.DIME , the compiler reports an error.
Enhancing an Enum
Youcanaddfields,constructors,andmethodstoanenum-youcanevenhavetheenum
implement interfaces. For example, Listing 3-62 adds a field, a constructor, and two
methodsto Coin toassociateadenominationvaluewitha Coin constant(suchas1for
penny and 5 for ickel) and convert pennies to the denomination.
Listing 3-62. Enhancing the Coin enum
enum Coin
{
PENNY(1),
NICKEL(5),
DIME(10),
QUARTER(25);
private final int denomValue;
Coin(int denomValue)
{
this.denomValue = denomValue;
}
int denomValue()
{
return denomValue;
}
int toDenomination(int umPennies)
{
return umPennies/denomValue;
}
}
 
Search WWH ::




Custom Search