Java Reference
In-Depth Information
which is always a good thing, and we avoided writing code that should
never get executed.
The classes that are defined for each enum constant are effectively an-
onymous inner classes that extend the enclosing enum typewhich is why
you can't actually declare an enum to be
final
: Even though it can't be
directly extended, it can be implicitly extended by these anonymous in-
ner classes.
As with other anonymous inner classes, the enum constant class body
can define arbitrary instance fields, and methods, but it can't declare
static members or define constructors. Also note that because enum
constants are implicitly static fields, these anonymous inner classes
have no enclosing instance.
To be directly accessible, the methods defined for each enum constant
must be declared as methods of the enum type itselfeither explicitly, as
above for
reachable
, or implicitly by an interface the enum implements.
An enum type is allowed to declare an
abstract
method, only if there is
an implementation of that method for each and every enum constant.
Exercise 6.5
: Redo Exercise 6.4 making
getColor
an abstract method
and defining constant-specific methods for each enum constant to re-
turn the correct
Color
object. Would you recommend using constant-
specific methods to do this?