Java Reference
In-Depth Information
Enums
An enumerated type isatypethatspecifiesanamedsequenceofrelatedconstantsasits
legalvalues.Themonthsinacalendar,thecoinsinacurrency,andthedaysoftheweek
are examples of enumerated types.
Java developers have traditionally used sets of named integer constants to represent
enumerated types. Because this form of representation has proven to be problematic,
Java 5 introduced the enum alternative.
Thissectionintroducesyoutoenums.Afterdiscussingtheproblemswithtraditional
enumerated types, the section presents the enum alternative. It then introduces you to
the Enum class, from which enums originate.
The Trouble with Traditional Enumerated Types
Listing3-59 declaresa Coin enumeratedtypewhosesetofconstantsidentifiesdifferent
kinds of coins in a currency.
Listing 3-59. An enumerated type identifying coins
class Coin
{
final static int PENNY = 0;
final static int ICKEL = 1;
final static int DIME = 2;
final static int QUARTER = 3;
}
Listing3-60 declaresa Weekday enumeratedtypewhosesetofconstantsidentifies
the days of the week.
Listing 3-60. An enumerated type identifying weekdays
class Weekday
{
final static int SUNDAY = 0;
final static int MONDAY = 1;
final static int TUESDAY = 2;
final static int WEDNESDAY = 3;
final static int THURSDAY = 4;
 
 
Search WWH ::




Custom Search