Java Reference
In-Depth Information
"+
Token.values()[i]);
}
}
Listing3-64 ' s main() methodcalls values() toreturnthearrayof Token con-
stants.Foreachconstant,itcallstheconstant's name() methodtoreturntheconstant's
name,andimplicitly calls toString() toreturntheconstant'svalue.Ifyouwereto
run this application, you would observe the following output:
Token values:
IDENTIFIER = ID
INTEGER = INT
LPAREN = (
RPAREN = )
COMMA = ,
Another way to enhance an enum is to assign a different behavior to each constant.
Youcanaccomplishthistaskbyintroducinganabstractmethodintotheenumandover-
ridingthismethodinananonymoussubclassoftheconstant. Listing3-65 's TempCon-
version enum demonstrates this technique.
Listing 3-65. Using anonymous subclasses to vary the behaviors of enum constants
enum TempConversion
{
C2F("Celsius to Fahrenheit")
{
@Override
double convert(double value)
{
return value*9.0/5.0+32.0;
}
},
F2C("Fahrenheit to Celsius")
{
@Override
double convert(double value)
{
Search WWH ::




Custom Search