Java Reference
In-Depth Information
public class SmartBoss
{
public void payEmployee(Employee e)
{
double pay = e.computePay();
System.out.println(“Just paid “ + e.getName() + “ $” + pay);
e.mailCheck();
}
}
Listing 8.11
The SmartBoss class takes advantage of virtual methods.
The payEmployee() method in the SmartBoss class simply invokes com-
putePay() on the Employee reference passed in, and at no time does the Smart-
Boss know or care what type of Employee object was actually passed in. At run
time, virtual method invocation occurs, and the appropriate computePay()
method is invoked in one of the child classes of Employee.
Notice that the SmartBoss also invokes mailCheck(), which appears in
the Employee class. The Salary class overrides mailCheck(), so when the
argument passed in is of type Salary, mailCheck() in Salary is invoked. The
Hourly class does not override mailCheck(), so the mailCheck() method in
Employee is invoked when an Hourly object is passed in to
payEmployee().
The PayDemo2 program in Listing 8.12 instantiates and pays several
employees. Study the program carefully, determine when virtual methods
apply, and try to determine the output, which is shown in Figure 8.5.
public class PayDemo2
{
public static void main(String [] args)
{
SmartBoss boss = new SmartBoss();
Salary s = new Salary(“Thomas Jefferson”, “Monticello, VA”,
3, 2600.00);
Hourly h = new Hourly(“John Adams”, “Boston, MA”, 2, 2.50);
h.setHoursWorked(40);
Employee e = new Employee(“George W.”, “Houston, TX”, 43);
System.out.println(“** Paying Salary object **”);
Listing 8.12
The PayDemo2 program pays employees using the SmartBoss.
Search WWH ::




Custom Search