Java Reference
In-Depth Information
Enumerated Types
Sometimes you need a simple type consisting of a short list of named values. For
example, the values might be clothing sizes, the days of the week, or some other brief
list. Starting with version 5.0, Java allows you to have such an enumerated type . For
example, the following is an enumerated type for the days of a five-day work week:
enumerated
type
enum WorkDay {MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY};
A value of an enumerated type is a kind of named constant and so, by convention, is
spelled with all uppercase letters. So, we used, for example, MONDAY , not Monday , in
the above definition of the enumerated type WorkDay . Using Monday would have been
legal, but poor style.
As with any other type, you can have variables of an enumerated type; for example,
WorkDay meetingDay, availableDay;
A variable of an enumerated type can have a value that must be either one of the
values listed in the definition of the type or else the special value null , which serves as
a placeholder indicating that the variable has no “real” value. For example, you can set
the value of a variable of an enumerated type with an assignment statement, as follows:
meetingDay = WorkDay.THURSDAY;
Note that when you write the value of an enumerated type, you need to preface the
name of the value, such as THURSDAY , with the name of the type. For example, you use
WorkDay.THURSDAY , not THURSDAY .
As with any other type, you can combine the declaration of a variable with the
assignment of a value to the variable, as in
WorkDay meetingDay = WorkDay.THURSDAY;
A program that demonstrates the syntax for using enumerated types is given in
Display 6.13. Be sure to notice that we placed the definition of the enumerated type
outside of the main method in the same place that you would give named constants.
Display 6.13
An Enumerated Type (part 1 of 2)
1 public class EnumDemo
2 {
3 enum WorkDay {MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY};
4 public static void main(String[] args)
5 {
6 WorkDay startDay = WorkDay.MONDAY;
7 WorkDay endDay = WorkDay.FRIDAY;
 
Search WWH ::




Custom Search