Java Reference
In-Depth Information
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 de-
fining 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 lan-
guage. For example, enum constants can be used directly with a switch
statement (see page 232 ) whereas normal object references can not. Un-
less you need specialization through subclassing, it will almost always be
better to use an enum type than to define your own classes.
C ENSUS T AKER TO H OUSEWIFE : Did you ever have the measles, and, if
so, how many?
 
Search WWH ::




Custom Search