Java Reference
In-Depth Information
We need to make our definition work for any kind of object. If the object is not
an
Employee
, we simply return
false
. The calling object is an
Employee
, so if the
argument is not an
Employee
, they should not be considered equal. But how can we
tell whether the parameter is or is not of type
Employee
?
Every object inherits the method
getClass()
from the class
Object
. The method
getClass()
is marked
final
in the class
Object
, so it cannot be overridden. For any
object
o
,
o.getClass()
returns a representation of the class used to create
o
. For example,
after the following is executed,
o = new Employee();
o.getClass()
returns a representation
Employee
.
We will not describe the details of this representation except to say that two
such representations should be compared with
==
or
!=
if you want to know if
two representations are the same. Thus,
if
(object1.getClass() == object2.getClass())
System.out.println("Same class.");
else
System.out.println("Not the same class.");
will output
"Same class."
if
object1
and
object2
were created with the same class
when they were created using
new
, and output
"Not the same class."
otherwise.
Our final version of the method
equals
is shown in Display 7.10 . Note that we
have also taken care of one more possible case. The predefined constant
null
can
be plugged in for a parameter of type
Object
. The Java documentation says that an
equals
method should return
false
when comparing an object and the value
null
.
So that is what we have done.
On the accompanying website, the subdirectory
improvedEquals
(of the directory
for this chapter) has a definition of the class
Employee
that includes this definition
of
equals
.
extra code
on website
Display 7.10
A Better
equals
Method for the Class
Employee
1
public boolean
equals(Object otherObject)
2 {
3
if
(otherObject ==
null
)
4
return false;
5
else if
(getClass() != otherObject.getClass())
6
return false;
7
else
8 {
9 Employee otherEmployee = (Employee)otherObject;
10
return
(name.equals(otherEmployee.name)
11 && hireDate.equals(otherEmployee.hireDate));
12 }
13 }