Polymorphism. Polymorphism , from a Greek word meaning multiform , means “capable of hav-
ing or occurring in several distinct forms”. The ability for a call like
e1.getCompensation() to call one of many different methods depending on
the value of e1 is a far more flexible form of polymorphism than the ad hoc
polymorphism mentioned in Chap. 2.
In ad hoc polymorphism, the method to be called is a syntactic property; it
determined at compile-time. In object-oriented polymorphism , the method to be
called cannot be determined until the call is to be executed at runtime, because
it depends entirely on e1's value, which can change at runtime.
Without OO polymorphism —the ability to have the real type determine
which method to call— OO would not be half as useful as a structuring tool.
If method getCompensation is overloaded, e.g. there is a method by that
name with an int parameter as well as a method with no parameters, e1.get-
Compensation() exhibits both ad hoc and OO polymorphism.
Employee d= c;
Just as Java automatically widens an int value to a double , Java widens the
instance of a class to an instance of one of its superclasses.
But what does widening an object mean? Widening an int to a double takes
time because a 4-byte value is changed into an 8-byte value with different char-
acteristics. Widening an object takes no time (at runtime) but just changes the
syntactic view of the object. Widening is best illustrated with an example.
Figure 4.5 shows on the left the syntactic view of object a1 as seen from c .
Apparently, c contains the name of an Executive , and references to all compo-
nents that are available in any instance of Executive are legal. So, calls
c.toString() and c.getBonus() are legal. We say that the apparent type of c
is Executive .
On the right is the syntactic view of the same object a1 as seen from d .
Apparently, d contains the name of an Employee , and references to all compo-
nents that are available in any instance of Employee are legal. So, the call
d.toString() is legal, but the call d.getBonus() is illegal. We say that the
apparent type of d is Employee .
We stress that the apparent type of an expression is a syntactic property. It
determines what component names can be referenced. If you write the call
d.getBonus() in your program, it will not compile.
The call d.toString() is legal. We now ask what it means —which method
it calls. According to the public overriding rule (see Sec. 4.1.1), it calls the
method toString that appears in the Executive partition of a1 . Thus, even
though the apparent class of d is Employee , d.toString() calls the overriding
method of Executive .
Apparently, d contains an Employee , but in reality, it contains an
Executive . We say that the apparent type of d is Employee , but its real type is