plain "constant" to refer to the latter.
Suit currentSuit = ... ;
if (currentSuit == Suit.DIAMONDS) ... ;
Each enum constant actually refers to an instance of the enum class. You cannot construct an instance of an
enum by using newit is as if the enum had no accessible constructors. You may only use those objects created
for the enum constants.
While this simple usage appears little different from declaring a set of named integer constants, it has the
significant difference of being completely type-safe: It is impossible to assign anything to a reference of type
Suit except one of the four defined Suit enum constants or null. As you will see, enums also provide
much more sophisticated usage than can be achieved with named integer constants.
Exercise 6.1: Define simple enums for the days of the week and traffic light colors.
Exercise 6.2: Redo your solution to Exercise 2.17 to use an enum to represent the TURN_LEFT and
TURN_RIGHT constants. What advantage is there to using the enum?
Exercise 6.3: Redefine the Verbose interface from Section 4.2.1 on page 121 to use an enum for the
verbosity level instead of integer constants.
6.2. Enum Declarations
An enum is a special kind of class, but an enum declaration has restrictions on its form and use that are
different from those of a normal class. An enum declaration is like a class declaration with two exceptions:
The keyword enum is used instead of class, and before declaring any class members (or initialization
blocks) an enum must first declare all of its enum constants. If an enum does declare anything other than its
enum constants, then the list of enum constants must be termi ated by a semicolon. For example, this variation
of Suit provides a method to tell you how many suits there are:
enum Suit {
CLUBS, DIAMONDS, HEARTS, SPADES;
public static int getSize() { return 4; }
}
For convenience, you're allowed to have a comma after the last enum constant (but before the semicolon if
present), whether or not any other class declarations follow. This is useful for declaring an enum constant per
line:
enum Suit {
CLUBS,
DIAMONDS,
HEARTS,
SPADES,
}
Being able to keep the extraneous comma allows you to reorder lines without having to remember to add the
comma to the old last line or remove it from the new last line. (Array initialization lists have the same