Java Reference
In-Depth Information
27
28
this .weeklySalary = weeklySalary;
29
}
30
31
// return salary
32
public double getWeeklySalary()
33
{
34
return weeklySalary;
35
}
36
37
// calculate earnings; implement interface Payable method that was
// abstract in superclass Employee
@Override
public double getPaymentAmount()
{
return getWeeklySalary();
}
38
39
40
41
42
43
44
45
// return String representation of SalariedEmployee object
46
@Override
47
public String toString()
48
{
49
return String.format( "salaried employee: %s%n%s: $%,.2f" ,
50
super .toString(), "weekly salary" , getWeeklySalary());
51
}
52
} // end class SalariedEmployee
Fig. 10.14 | SalariedEmployee class that implements interface Payable method
getPaymentAmount . (Part 2 of 2.)
When a class implements an interface, the same is-a relationship provided by inheri-
tance applies. Class Employee implements Payable , so we can say that an Employee is a
Payable . In fact, objects of any classes that extend Employee are also Payable objects. Sal-
ariedEmployee objects, for instance, are Payable objects. Objects of any subclasses of the
class that implements the interface can also be thought of as objects of the interface type.
Thus, just as we can assign the reference of a SalariedEmployee object to a superclass
Employee variable, we can assign the reference of a SalariedEmployee object to an inter-
face Payable variable. Invoice implements Payable , so an Invoice object also is a Pay-
able object, and we can assign the reference of an Invoice object to a Payable variable.
Software Engineering Observation 10.9
When a method parameter is declared with a superclass or interface type, the method
processes the object passed as an argument polymorphically.
Software Engineering Observation 10.10
Using a superclass reference, we can polymorphically invoke any method declared in the
superclass and its superclasses (e.g., class Object ). Using an interface reference, we can
polymorphically invoke any method declared in the interface, its superinterfaces (one
interface can extend another) and in class Object —a variable of an interface type must
refer to an object to call methods, and all objects have the methods of class Object .
 
Search WWH ::




Custom Search