Java Reference
In-Depth Information
The Boss class in Listing 8.6 contains a payEmployee() method with an
Employee parameter. The method casts the parameter to its appropriate data
type and invokes computePay().
public class Boss
{
public void payEmployee(Employee e)
{
double pay = 0.0;
if(e instanceof Salary)
{
pay = ((Salary) e).computePay();
}
else if(e instanceof Hourly)
{
pay = ((Hourly) e).computePay();
}
System.out.println(“Pay = “ + pay);
e.mailCheck();
}
}
Listing 8.6
The Boss class demonstrates polymorphic parameters.
The payEmployee() method in the Boss class cannot simply invoke com-
putePay() on the parameter e because the parameter is an Employee type, and
the Employee class does not contain a computePay() method. To invoke com-
putePay(), the reference e must be cast to its appropriate data type, which is
determined by using the instanceof keyword. Notice that the mailCheck()
method can be invoked without casting because mailCheck() is in the
Employee class and e is an Employee reference.
The payEmployee() method can be invoked passing in any Employee
object. If a new Contractor class is written that extends Employee,
Contractor objects can be passed into the existing payEmployee() method
without changing the method's signature.
Unfortunately, we would have to modify the body of payEmployee() and
add an instanceof check for Contractor, which is not good design. In the
upcoming Taking Advantage of Virtual Methods section, I will show
you a payEmployee() method that can pay all Employee objects without
requiring modification when new child classes of Employee come along.
Search WWH ::




Custom Search