Java Reference
In-Depth Information
defined in the
Object
class, it can be used to compare any two objects. However, the default
implementation in the
Object
class is equivalent to the “==” operator: it just checks if the
two objects are identical. Consider the following rewrite.
Superhero s1 =
new
Superhero(
"Superman"
,5,5) ;
Superhero s2 =
new
Superhero(
"Superman"
,5,5) ;
if
(s1.equals(s2))
{
...
}
If the
Superhero
does not override the
equals
method, then the condition in the
if
state-
ment will be false again because the two objects are distinct. In order for the condition to
be true, we need to override the
equals
method in the
Superman
class by defining what
does it mean for two Supermans to be equal. Let us start with the
FictionalCharacter
class.
public class
FictionalCharacter
{
private
String name;
...
public boolean
equals(Object other)
{
if
(other . getClass ()!= getClass ())
{
return false
;
return
name. equals (((FictionalCharacter)other) .name) ;
}
}
The
equals
method compares the input object to the
this
object. If they have different
runtime types, then the objects cannot be the same. If they have the same runtime type, then
the input object must be of type
FictionalCharacter
. It therefore must have the attribute
name
and we can simply compare the names of the two objects. Remember that strings
should always be compared using the
equals
method. The reason is that the creators of the
String
class created a meaningful
equals
method for objects of type
String
. Remember as
well that the input to the
equals
method in the class
Object
is of type
Object
. Therefore,
when we override the
equals
method, we must perform the following tasks.
1. Determine the type of the input object.
2. Cast the input object to the appropriate type.
3. Compare the variables of the two objects.
Extra care should be taken when creating classes that have both the
equals
and
compareTo
methods. Although not required, it is good programming practice that
o1.equals(o2)
is true exactly when
o1.compareTo(o2)==0
.
Next, let us focus on the
Superhero
class and its equal methods.
public class
Superhero
extends
FictionalCharacter
{
private int
goodPower ;
private int
respect ;
...
public boolean
equals(Object other)
{
if
(!
super
.equals(other))
{
return false
;