Java Reference
In-Depth Information
In Fig. 6.8, we introduced the basic
enum
type, which defines a set of constants represented
as unique identifiers. In that program the
enum
constants represented the game's status. In
this section we discuss the relationship between
enum
types and classes. Like classes, all
enum
types are
reference
types. An
enum
type is declared with an
enum
declaration
, which is
a comma-separated list of
enum
constants
—the declaration may optionally include other
components of traditional classes, such as constructors, fields and methods (as you'll see
momentarily). Each
enum
declaration declares an
enum
class with the following restrictions:
1.
enum
constants are
implicitly
final
.
2.
enum
constants are
implicitly
static
.
3.
Any attempt to create an object of an
enum
type with operator
new
results in a
compilation error.
The
enum
constants can be used anywhere constants can be used, such as in the
case
labels
of
switch
statements and to control enhanced
for
statements.
Declaring Instance Variables, a Constructor and Methods in an
enum
Type
Figure 8.10 demonstrates instance variables, a constructor and methods in an
enum
type.
The
enum
declaration (lines 5-37) contains two parts—the
enum
constants and the other
members of the
enum
type. The first part (lines 8-13) declares six constants. Each is op-
tionally followed by arguments that are passed to the
enum
constructor
(lines 20-24). Like
the constructors you've seen in classes, an
enum
constructor can specify any number of pa-
rameters and can be overloaded. In this example, the
enum
constructor requires two
String
parameters. To properly initialize each
enum
constant, we follow it with parentheses con-
taining two
String
arguments. The second part (lines 16-36) declares the other members
of the
enum
type—two instance variables (lines 16-17), a constructor (lines 20-24) and
two methods (lines 27-30 and 33-36).
Lines 16-17 declare the instance variables
title
and
copyrightYear
. Each
enum
con-
stant in
enum
type
Book
is actually an object of
enum
type
Book
that has its own copy of
instance variables
title
and
copyrightYear
. The constructor (lines 20-24) takes two
String
parameters, one that specifies the topic's title and one that specifies its copyright
year. Lines 22-23 assign these parameters to the instance variables. Lines 27-36 declare
methods, which return the topic title and copyright year, respectively.
1
// Fig. 8.10: Book.java
2
// Declaring an enum type with a constructor and explicit instance fields
3
// and accessors for these fields
4
5
public enum
Book
6
{
7
// declare constants of enum type
JHTP(
"Java How to Program"
,
"2015"
),
CHTP(
"C How to Program"
,
"2013"
),
IW3HTP(
"Internet & World Wide Web How to Program"
,
"2012"
),
8
9
10
Fig. 8.10
|
Declaring an
enum
type with a constructor and explicit instance fields and accessors
for these fields. (Part 1 of 2.)