Java Reference
In-Depth Information
avoid casting down the hierarchy tree, I will. It saves me from having to use
instanceof, and it improves the maintenance of my code when I do have to
worry about what type an object is.
Classroom Q & A
Q: In the Boss class, why did you cast the Employee parameter to
either a Salary or Hourly reference?
A: I wanted to invoke computePay() on the parameter, but there are
two computePay() methods: one in Salary, and one in Hourly. I
had to cast the parameter to its appropriate type so I could explic-
itly invoke the proper computePay() method.
Q: But you just said all methods in Java are virtual by default. Why
didn't the JVM at runtime figure out which computePay() method
to invoke?
A: You cannot invoke computePay() with an Employee reference
because there is no computePay() method in the Employee class.
Plus, virtual methods only apply to overridden methods. The
computePay() methods in Salary and Hourly are not overriding
anything.
Q: Why don't we just put computePay() in the Employee class so that
we can take advantage of virtual methods?
A: Good idea. In fact, we will do that next and see what happens.
This points out a flaw in the design of our employee program. We
started this example with the idea that our program would pay
employees on a weekly basis. We quickly discovered that we had
different types of employees, depending on how they were paid.
Subclassing Employee is a good design because it allows us to write
multiple computePay() methods, instead of a single, decision-filled
computePay() method that has to determine which formula to use
based on how the employee is paid. In the process of subclassing
Employee, however, we removed computePay() from our Employee
class entirely.
Q: That's because all the information to compute an employee's pay
is in one of the child classes. Why put computePay() in the
Employee class when the data it needs is down in a child class?
A: It's a design issue. I think we should put computePay() back in the
Employee class because, from the outset, we wanted to be able to
compute an employee's pay. Therefore, one of the behaviors of
the Employee class should be computePay().
Search WWH ::




Custom Search