Java Reference
In-Depth Information
80
// method required to carry out contract with interface Payable
@Override
public double getPaymentAmount()
{
return getQuantity() * getPricePerItem(); // calculate total cost
}
81
82
83
84
85
86
} // end class Invoice
Fig. 10.12 | Invoice class that implements Payable . (Part 3 of 3.)
A Class Can Extend Only One Other Class But Can Implement Many Interfaces
Line 4 indicates that class Invoice implements interface Payable . Like all classes, class In-
voice also implicitly extends Object . Java does not allow subclasses to inherit from more
than one superclass, but it allows a class to inherit from one superclass and implement as
many interfaces as it needs. To implement more than one interface, use a comma-separated
list of interface names after keyword implements in the class declaration, as in:
public class ClassName extends SuperclassName implements FirstInterface ,
SecondInterface ,
Software Engineering Observation 10.8
All objects of a class that implements multiple interfaces have the is-a relationship with
each implemented interface type.
Class Invoice implements the one abstract method in interface Payable —method
getPaymentAmount is declared in lines 81-85. The method calculates the total payment
required to pay the invoice. The method multiplies the values of quantity and pricePer-
Item (obtained through the appropriate get methods) and returns the result. This method
satisfies the implementation requirement for this method in interface Payable —we've ful-
filled the interface contract with the compiler.
10.9.4 Modifying Class Employee to Implement Interface Payable
We now modify class Employee such that it implements interface Payable . Figure 10.13
contains the modified class, which is identical to that of Fig. 10.4 with two exceptions.
First, line 4 of Fig. 10.13 indicates that class Employee now implements interface Payable .
For this example, we renamed method earnings to getPaymentAmount throughout the
Employee hierarchy. As with method earnings in the version of class Employee in
Fig. 10.4, however, it does not make sense to implement method getPaymentAmount in
class Employee because we cannot calculate the earnings payment owed to a general Em-
ployee —we must first know the specific type of Employee . In Fig. 10.4, we declared meth-
od earnings as abstract for this reason, so class Employee had to be declared abstract .
This forced each Employee concrete subclass to override earnings with an implementation.
1
// Fig. 10.13: Employee.java
2
// Employee abstract superclass that implements Payable.
3
Fig. 10.13 | Employee abstract superclass that implements Payable . (Part 1 of 2.)
 
 
Search WWH ::




Custom Search