Java Reference
In-Depth Information
•
clone()
isoverriddentopreventconstantsfrombeingclonedsothatthereis
evermorethanonecopyofaconstant;otherwise,constantscouldnotbecom-
pared via
==
.
•
equals()
isoverriddentocompareconstantsviatheirreferences—constants
with the same identities (
==
) must have the same contents (
equals()
), and
different identities imply different contents.
•
finalize()
is overridden to ensure that constants cannot be finalized.
•
hashCode()
is overridden because
equals()
is overridden.
•
toString()
is overridden to return the constant's name.
Exceptfor
toString()
,alloftheoverridingmethodsaredeclared
final
sothat
they cannot be overridden in a subclass.
Enum
also provides its own methods. These methods include the
final com-
pareTo()
, (
Enum
implements
Comparable
),
getDeclaringClass()
,
name()
, and
ordinal()
methods:
•
compareTo()
compares the current constant with the constant passed as an
argument to see which constant precedes the other constant in the enum, and
returnsavalueindicatingtheirorder.Thismethodmakesitpossibletosortan
array of unsorted constants.
•
getDeclaringClass()
returns the
Class
object corresponding to the
currentconstant'senum.Forexample,the
Class
objectfor
Coin
isreturned
whencalling
Coin.PENNY.getDeclaringClass()
for
enum Coin {
PENNY, ICKEL, DIME, QUARTER }
. Also,
TempConversion
is
returnedwhencalling
TempConversion.C2F.getDeclaringClass()
uses
Class
's
getClass()
methodand
Enum
's
getDeclaringClass()
methodtoensurethatonlyconstantsbelongingtothesameenumarecompared.
Otherwise, a
ClassCastException
is thrown. (I will discuss
Class
in
•
name()
returns the constant's name. Unless overridden to return something
more descriptive,
toString()
also returns the constant's name.
•
ordinal()
returnsazero-based
ordinal
,anintegerthatidentifiestheposition
of the constant within the enum type.
compareTo()
compares ordinals.
Enum
also provides the
public static <T extends Enum<T>> T
valueOf(Class<T> enumType, String name)
method for returning the
enum constant from the specified enum with the specified name: