THE Java™ Programming Language, Fourth Edition

(Jeff_L) #1

In addition to the Enum class, there are two highly efficient enum-specific collection classes: EnumSet
defines a set for use with enum values, and EnumMap is a specialized map for which keys are enum values.
These specialized collection classes are described further in Chapter 21.


6.5. To Enum or Not


The more sophisticated the type you are considering defining as an enum, the more thought you must give to
whether enum is the right way to express that type. For simple uses like card suits, days of the week, and even
the simple chess piece enum, all that is necessary is that you have a closed set of well-known instancesthe
decision to define an enum takes almost no thought.


When an enum declares enum constants with constant-specific behavior, additional considerations need to be
made. The more sophisticated the behavior of a type, the more likely an application might need to specialize
that behavior. Specialization of behavior is done through subclassing, and you cannot subclass an enum. Even
something as innocuous as defining a logging, or profiling version of a given enum type is precluded. The
same considerations that go into declaring a class final apply to choosing whether to declare a sophisticated
enum.


There is little an enum can do that you couldn't do by declaring distinct classes. But the packaging that enum
provides is far more convenient to use, though with some restrictions, as you've seen. Additionally, enums are
a part of the language and are recognized by other parts of the language. For example, enum constants can be
used directly with a switch statement (see page 232) whereas normal object references can not. Unless you
need specialization through subclassing, it will almost always be better to use an enum type than to define
your own classes.


CENSUS TAKER TO HOUSEWIFE: Did you ever have the measles, and, if so, how many?

Chapter 7. Tokens, Values, and Variables


There's nothing remarkable about it. All one has to do is hit the right keys at the right time
and the instrument plays itself.

Johann Sebastian Bach

A program starts as a sequence of characters contained in a filethe source code. Interpreting those characters,
according to the rules of a given language, is the job of the compiler, or interpreter. Some characters will
represent the names of variables, others will be special keywords used by the language, still others will be
operators or "punctuation" characters used to separate the other elements. All of these textual constructs form
the lexical elements of the program. These lexical elements must be identified as keywords, comments,
literals, variables, operators, or whatever else is appropriate for the given language. In this chapter we look at
the basic lexical elements of a Java program, the literal values that can be expressed and the different kinds of
variables that can hold those values.

Free download pdf