Java Reference
In-Depth Information
Q: What is the computePay() method in Employee going to do?
A: For now, we will add a computePay() method to Employee that
returns 0.0, as seen in Listing 8.10, just so we can override it in
Salary and Hourly and take advantage of virtual methods.
public class Employee
{
private String name;
private String address;
private int number;
public double computePay()
{
System.out.println(“Inside Employee computePay”);
return 0.0;
}
public void mailCheck()
{
System.out.println(“Mailing a check to “ + this.name
+ “ “ + this.address);
}
//Remainder of class definition...
}
Listing 8.10
The Employee class with a computePay() method added.
With computePay() in the Employee class and also in the Salary and Hourly
classes, the following statements now compile:
Employee e = new Salary(“George Washington”, “Valley Forge, DE”,
1, 5000.00);
e.computePay();
More important than compiling, the previous statements behave in the
manner that we want. The compiler sees computePay() in the Employee class,
which simply returns 0.0. At run time, however, the JVM invokes com-
putePay() in the Salary class because e references a Salary object.
The SmartBoss class in Listing 8.11 is a modification of the Boss class. The
payEmployee() method in the SmartBoss takes advantage of virtual methods,
and does not need to worry about casting or using the instanceof operator.
Search WWH ::




Custom Search