Java Reference
In-Depth Information
Now that we have written the interfaces, we need a class to implement
them. But in our example, the Employee class already implements these meth-
ods, so all we need to do is make a quick change to Employee, having it declare
that it implements both Payable and EmployeeInfo, as shown here:
public class Employee implements Payable, EmployeeInfo
{
//The class definition remains the same.
}
By implementing Payable and EmployeeInfo, through polymorphism an
Employee object becomes a Payable object and an EmployeeInfo object. If
someone in payroll needs an Employee object, we can pass the Employee
object to a Payable reference. If someone in human resources needs an
Employee object, we can pass the Employee object to an EmployeeInfo
reference. With a Payable reference, only the Payable methods can be
invoked. With an EmployeeInfo reference, only the methods in
EmployeeInfo can be invoked.
In Chapter 8, “Polymorphism and Abstraction,” we saw a SmartBoss class
that has a payEmployee() method with an Employee parameter. This allows
SmartBoss to pay any Employee object. The SmartBoss can use the Employee
reference and invoke any of the methods in the Employee class.
The following Payroll class represents the Payroll Department of the com-
pany. The parameter of payEmployee() in Payroll is a Payable reference, mean-
ing that we can pass in any object that is of type Payable. Because the
Employee class implements Payable, Employee objects are of type Payable, so
we can pass Employee objects in to the Payable reference of the payEm-
ployee() method.
public class Payroll
{
public void payEmployee(Payable p)
{
p.computePay(40);
p.mailCheck();
}
public void printPaycheck(Payable p)
{
System.out.println(“Printing check for $” + p.getWeeklyPay());
}
}
Search WWH ::




Custom Search