2017-04-10 11:06:08
10.3  Demonstrating Polymorphic Behavior
399
ward—as in Section 9.4, we assign a superclass
reference to a superclass variable, and a
subclass reference to a subclass variable. Then we demonstrate the relationship between
subclasses and superclasses (i.e., the
is-a
relationship) by assigning a subclass reference to a
superclass variable. This program uses classes
CommissionEmployee
and
BasePlusCommis-
sionEmployee
from Fig. 9.10 and Fig. 9.11, respectively.
1
// Fig. 10.1: PolymorphismTest.java
2
// Assigning superclass and subclass references to superclass and
3
// subclass variables.
4
5
public class
PolymorphismTest
6
{
7
public static void
main( String[] args )
8
{
9
10
11
12
13
14
15
16
17
18
// invoke toString on superclass object using superclass variable
19
System.out.printf(
"%s %s:\n\n%s\n\n"
,
20
"Call CommissionEmployee's toString with superclass reference "
,
21
"to superclass object"
,);
22
23
// invoke toString on subclass object using subclass variable
24
System.out.printf(
"%s %s:\n\n%s\n\n"
,
25
"Call BasePlusCommissionEmployee's toString with subclass"
,
26
"reference to subclass object"
,
27
);
28
29
// invoke toString on subclass object using superclass variable
30
31
32
System.out.printf(
"%s %s:\n\n%s\n"
,
33
"Call BasePlusCommissionEmployee's toString with superclass"
,
34
"reference to subclass object"
,);
35
}
// end main
36
}
// end class PolymorphismTest
Invalid Email or Password