Java Reference
In-Depth Information
470
C
OMMON
E
RROR
10.6: Defining the
equals
Method
with the Wrong Parameter
Type
Consider the following, seemingly simpler, version of the
equals
method for
the
Coin
class:
public boolean equals(
Coin
other) //
DonȐt do this!
{
return name.equals(other.name) && value ==
other.value;
}
Here, the parameter of the
equals
method has the type
Coin
, not
Object
.
Unfortunately, this method does not override the
equals
method in the
Object
class. Instead, the
Coin
class now has two different
equals
methods:
boolean equals(Coin other) //
Defined in the
Coin
class
boolean equals(Object otherObject) //
Inherited from the
Object
class
This is error-prone because the wrong
equals
method can be called. For
example, consider these variable definitions:
Coin aCoin = new Coin(0.25, ÐquarterÑ);
Object anObject = new Coin(0.25, ÐquarterÑ);
The call
aCoin.equals (anObject)
calls the second
equals
method,
which returns
false
.
The remedy is to ensure that you use the
Object
type for the explicit parameter
of the
equals
method.