Java Reference
In-Depth Information
9 System.out.println(
"day2's ordinal is "
+ day2.ordinal());
10
11 System.out.println(
"day1.equals(day2) returns "
+
12 day1.equals(day2));
13 System.out.println(
"day1.toString() returns "
+
14 day1.toString());
15 System.out.println(
"day1.compareTo(day2) returns "
+
16
day1.compareTo(day2));
17 }
18 }
19
20
enum
Day {SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY,
21
FRIDAY, SATURDAY}
An enumerated type can be defined inside a class, as shown in lines 2-3 in Listing I.1, or
standalone as shown in lines 20-21 Listing I.2. In the former case, the type is treated as an
inner class. After the program is compiled, a class named EnumeratedTypeDemo$Day.class
is created. In the latter case, the type is treated as a standalone class. After the program is
compiled, a class named Day.class is created.
Note
When an enumerated type is declared inside a class, the type must be declared as a
member of the class and cannot be declared inside a method. Furthermore, the type is
always
static
. For this reason, the
static
keyword in line 2 in Listing I.1 may be
omitted. The visibility modifiers on inner class can be also be applied to enumerated
types defined inside a class.
Tip
Using enumerated values (e.g.,
Day.MONDAY
,
Day.TUESDAY
, and so on) rather than
literal integer values (e.g., 0, 1, and so on) can make program easier to read and maintain.
I.2 Using
if
or
switch
Statements with an
Enumerated Variable
An enumerated variable holds a value. Often your program needs to perform a specific action
depending on the value. For example, if the value is
Day.MONDAY
, play soccer; if the value is
Day.TUESDAY
, take piano lesson, and so on. You can use an
if
statement or a
switch
state-
ment to test the value in the variable, as shown in (a) and (b)
if
(day.equals(Day.MONDAY)) {
// process Monday
switch
(day) {
case
MONDAY:
// process Monday
break
;
case
TUESDAY:
// process Tuesday
break
;
...
}
}
else if
(day.equals(Day.TUESDAY)) {
// process Tuesday
Equivalent
}
else
...
(a)
(b)
In the
switch
statement in (b), the case label is an unqualified enumerated value (e.g.,
MONDAY
, but not
Day.MONDAY
).
Search WWH ::
Custom Search