Java Reference
In-Depth Information
6.1. A Simple Enum Example
An enum for the suits in a deck of cards can be declared as follows:
enum Suit { CLUBS, DIAMONDS, HEARTS, SPADES }
In this basic form, an enum declaration consists of the keyword enum , an
identifier that names the enum, and a body that simply names each of
the values, or constants, of the enum. [1] By convention, enum constants
always have uppercase names. The enum constants are static fields of
the class:
[1] The term enum constant refers to those values, like CLUBS and DIAMONDS , declared in the enum type.
Enum types can also have normal constants, just like other classes, that are static final fields of various
types. We always use "enum constant" to refer to the former, and 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 new it 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 com-
pletely 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.
 
 
Search WWH ::




Custom Search