Java Reference
In-Depth Information
TIP:
getClass
versus
instanceof
★
Many authors suggest that in the definition of
equals
for a class such as
Employee
,
given in Display 7.10, you should not use
else if
(getClass() != otherObject.getClass())
return false
;
but should instead use
else if
(!(otherObject
instanceof
Employee))
return false
;
What is the difference and which should you use? At first glance, it seems like you
should use
instanceof
in the definition of
equals
. The
instanceof
operator
checks to see if an object is of the type given as its second argument. The syntax is
instanceof
Object
instanceof
Class_Name
which returns
true
if
Object
is of type
Class_Name
; otherwise it returns
false
. So,
the following will return
true
if
otherObject
is of type
Employee
:
(otherObject
instanceof
Employee)
Suppose that (contrary to what we really did) we instead used
instanceof
in
our definition of
equals
for the class
Employee
and also used
instanceof
in
our definition for the class
HourlyEmployee
, so that the definition of
equals
for
HourlyEmployee
is as follows:
public boolean
equals(Object otherObject)
//This is NOT the right way to define equals.
{
if
(otherObject ==
null
)
return false
;
else if
(!(otherObject
instanceof
HourlyEmployee))
return false
;
else
{
HourlyEmployee otherHourlyEmployee =
(HourlyEmployee)otherObject;
return
(
super
.equals(otherHourlyEmployee)
&& (wageRate == otherHourlyEmployee.wageRate)
&& (hours == otherHourlyEmployee.hours));
}
}
(continued)