Java Reference
In-Depth Information
Another method inherited from the class
Object
is the method
clone
, which
is intended to return a copy of the calling object. We discuss the method
clone
in
Chapters 8 and 13 .
clone
The Right Way to Define
equals
Earlier we said that the class
Object
has an
equals
method, and that when you define
a class with an
equals
method, you should override the definition of the method
equals
given in the class
Object
. However, we did not, strictly speaking, follow
our own advice. The heading for the method
equals
in our definition of the class
Employee
( Display 7.2 ) is as follows:
public boolean
equals(Employee otherEmployee)
On the other hand, the heading for the method
equals
in the class
Object
is as
follows:
public boolean
equals(Object otherObject)
The two
equals
methods have different parameter types, so we have not overridden
the definition of
equals
We have merely overloaded the method
equals
. The class
Employee
has both of these methods named
equals
.
In most situations, this will not matter. However, there are situations in which it
does. Some library methods assume your class's definition of
equals
has the following
heading, the same as in the class
Object
:
public boolean
equals(Object otherObject)
We need to change the type of the parameter for the
equals
method in the
class
Employee
from type
Employee
to type
Object
. A first try might produce
the following:
public boolean
equals(Object otherObject)
{
Employee otherEmployee = (Employee)otherObject;
return
(name.equals(otherEmployee.name)
&& hireDate.equals(otherEmployee.hireDate));
}
We needed to type cast the parameter
otherObject
from type
Object
to type
Employee
. If we omit the type cast and simply proceed with
otherObject
, the
compiler will give an error message when it sees the following:
otherObject.name
The class
Object
does not have an instance variable named
name
.
This first try at an improved
equals
method does override the definition of
equals
given in the class
Object
and will work well in many cases. However, it still has
a shortcoming.
Our definition of
equals
now allows an argument that can be any kind of object
whatsoever. What happens if the method
equals
is used with an argument that is not
an
Employee
? A run-time error will occur when the type cast to
Employee
is executed.