Java Reference
In-Depth Information
6.4.
java.lang.Enum
to extend
Enum
directly. Although
Enum
does provide some methods that
can be useful for working with enums, its main role is to establish some
useful properties for all enum types:
[3]
Enum
is actually a generic class defined as
Enum<T extends Enum<T>>.
This circular definition is prob-
ably the most confounding generic type definition you are likely to encounter. We're assured by the type
theorists that this is quite valid and significant, and that we should simply not think about it too much, for
which we are grateful.
•
The
clone
method is overridden to be declared
final
and to throw
CloneNotSupportedException
making it impossible to ever clone an
enum instance.
•
The
hashCode
and
equals
methods are overridden and declared
fi-
nal
ensuring consistent and efficient hashing for enums, and ensur-
ing that equivalence is the same as identity.
•
The
compareTo
method of interface
java.lang.Comparable
is imple-
mented and defined such that enum constants have a natural or-
dering based on their order of declarationthe first declared enum
constant has the lowest position in the ordering.
Enum also provides a
toString
implementation that returns the name of
the enum constant, as we have mentioned, but which you can chose to
override. It also provides a
finalname
method that also returns the name
of the enum constant as a
String
. The difference between these two
methods is that
name
will return the exact name of the enum constant,
while
toString
may be overridden to return a more "user friendly" version
of the namefor example, returning
"Diamonds"
instead of
"DIAMONDS"
.
The additional methods of
Enum
are:
public final int
ordinal()