Java Reference
In-Depth Information
EXAMPLES
Suppose that
HourlyEmployee
is a derived class of
Employee
and that
employeeObject
and
hourlyEmployeeObject
are created as follows:
Employee employeeObject =
new
Employee();
HourlyEmployee hourlyEmployeeObject =
new
HourlyEmployee();
Then:
employeeObject.getClass() == hourlyEmployeeObject.getClass()
returns
false
.
employeeObject
instanceof
Employee
returns
true
.
hourlyEmployeeObject
instanceof
Employee
returns
true
.
employeeObject
instanceof
HourlyEmployee
returns
false
.
hourlyEmployeeObject
instanceof
HourlyEmployee
returns
true
.
Self-Test Exercises
18. Redefine the method
equals
given in Display 7.10 using
instanceof
instead of
getClass()
. Give the complete definition. Remember, we do not want you to
define
equal
s this way in your class definitions; this is just an exercise.
19. Redefine the
equals
method of the class
HourlyEmployee
(Display 7.3) so that it
has a parameter of type
Object
and follows the other guidelines we gave for an
equals
method. Assume the definition of the method
equals
for the class
Employee
has been changed to be as in Display 7.10. (Remember, you should use
getClass()
, not
instanceof
.)