Java Reference
In-Depth Information
Figure 9.7
Method lookup with
polymorphism and
overriding
YGLVSOD\
Post
GLVSOD\
PhotoPost
GLVSOD\
instance of
3RVWY
3KRWR3RVW
This scenario is the most important one for understanding the behavior of our network
application and in finding a solution to our display method problem.
The steps in which method execution takes place are exactly the same as steps 1 through 4 from
scenario 1. Read them again.
Some observations are worth noting:
No special lookup rules are used for method lookup in cases where the dynamic type is not
equal to the static type. The behavior we observe is a result of the general rules.
Which method is found first and executed is determined by the dynamic type, not the static type.
In other words, the fact that the declared type of the variable v1 is now Post does not have any
effect. The instance we are dealing with is of class PhotoPost —that is all that counts.
Overriding methods in subclasses take precedence over superclass methods. Because method
lookup starts in the dynamic class of the instance (at the bottom of the inheritance hierarchy),
the last redefinition of a method is found first, and this is the one that is executed.
When a method is overridden, only the last version (the one lowest in the inheritance
hierarchy) is executed. Versions of the same method in any superclasses are not also
automatically executed.
This explains the behavior that we observe in our network project. Only the display methods
in the subclasses ( MessagePost and PhotoPost ) are executed when posts are printed out,
leading to incomplete listings. In the next section, we discuss how to fix this.
9.5
Super call in methods
Now that we know in detail how overridden methods are executed, we can understand the
solution to the problem. It is easy to see that what we would want to achieve is for every call to
a display method of, say, a PhotoPost object, to result in both the display method of the
 
Search WWH ::




Custom Search