Java Reference
In-Depth Information
Polymorphically
PayableInterfaceTest
(Fig. 10.15) illustrates that interface
Payable
can be used to pro-
cess a set of
Invoice
s and
Employee
s
polymorphically
in a single application. Line 9 declares
payableObjects
and assigns it an array of four
Payable
variables. Lines 12-13 assign the
references of
Invoice
objects to the first two elements of
payableObjects
. Lines 14-17
then assign the references of
SalariedEmployee
objects to the remaining two elements of
payableObjects
. These assignments are allowed because an
Invoice
is a
Payable
, a
Sal-
ariedEmployee
is an
Employee
and an
Employee
is a
Payable
. Lines 23-29 use the en-
hanced
for
statement to
polymorphically
process each
Payable
object in
payableObjects
,
printing the object as a
String
, along with the payment amount due. Line 27 invokes
method
toString
via a
Payable
interface reference, even though
toString
is not declared
in interface
Payable
—
all references (including those of interface types) refer to objects that ex-
tend
Object
and therefore have a
toString
method.
(Method
toString
also can be invoked
implicitly
here.) Line 28 invokes
Payable
method
getPaymentAmount
to obtain the pay-
ment amount for each object in
payableObjects
,
regardless
of the actual type of the object.
The output reveals that each of the method calls in lines 27-28 invokes the appropriate
class's implementation of methods
toString
and
getPaymentAmount
. For instance, when
currentPayable
refers to an
Invoice
during the first iteration of the
for
loop, class
In-
voice
's
toString
and
getPaymentAmount
execute.
1
// Fig. 10.15: PayableInterfaceTest.java
2
// Payable interface test program processing Invoices and
3
// Employees polymorphically.
4
public
class
PayableInterfaceTest
5
{
6
public
static
void
main(String[] args)
7
{
8
// create four-element Payable array
9
Payable[] payableObjects =
new
Payable[
4
];
10
11
// populate array with objects that implement Payable
12
payableObjects[
0
] =
new
Invoice(
"01234"
,
"seat"
,
2
,
375.00
);
13
payableObjects[
1
] =
new
Invoice(
"56789"
,
"tire"
,
4
,
79.95
);
14
payableObjects[
2
] =
15
new
SalariedEmployee(
"John"
,
"Smith"
,
"111-11-1111"
,
800.00
);
16
payableObjects[
3
] =
17
new
SalariedEmployee(
"Lisa"
,
"Barnes"
,
"888-88-8888"
,
1200.00
);
18
19
System.out.println(
20
"Invoices and Employees processed polymorphically:"
);
21
22
// generically process each element in array payableObjects
23
for
(Payable currentPayable : payableObjects)
24
{
Fig. 10.15
|
Payable
interface test program processing
Invoice
s and
Employee
s
polymorphically. (Part 1 of 2.)