Java Reference
In-Depth Information
TIP: (continued)
Assuming that the equals method for both Employee and HourlyEmployee are
defined using instanceof (as previously mentioned), consider the following situation:
Employee e =
new Employee("Joe Worker", new Date("January", 1, 2004));
HourlyEmployee hourlyE = new HourlyEmployee("Joe Worker",
new Date("January", 1, 2004), 50.50, 160);
Then, with the definition of equals that uses instanceof , we get that
e.equals(hourlyE)
returns true , because hourlyE is an Employee with the same name and hire date as e .
So far, it sounds reasonable.
However, since we are assuming that we also used instanceof in the defi nition of
equals for the class HourlyEmployee , we also get that
hourlyE.equals(e)
returns false because e instanceof HourlyEmployee returns false . ( e is an
Employee but e is not an HourlyEmployee .)
So, if we defi ne equals in both classes using instanceof , then e equals hourlyE ,
but hourlyE does not equal e . That is no way for equals to behave.
Since instanceof does not yield a suitable defi nition of equals , you should instead
use getClass() as we did in Display 7.10. If we use getClass() in a similar way in
the defi nition of equals for the class HourlyEmployee (see Self-Test Exercise 19 ), then
e.equals(hourlyE)
and
hourlyE.equals(e)
both return false .
Search WWH ::




Custom Search