Java Reference
In-Depth Information
Dynamic method lookup
One surprising detail is what exactly is printed once we execute the news feed's show method.
If we again create and enter the objects described in Section 9.1, the output of the show method
in our new version of the program is
Had a great idea this morning.
But now I forgot what it was. Something to do with flying ...
I think I might call this thing 'telephone'.
We can see from this output that the display methods in MessagePost and in PhotoPost
were executed, but not the one in Post .
This may seem strange at first. Our investigation in Section 9.2 has shown that the compiler
insisted on a display method in class Post —methods in the subclasses were not enough.
This experiment now shows that the method in class Post is then not executed at all, but the
subclass methods are. In short:
Type checking uses the static type, but at runtime, the methods from the dynamic type are
This is a fairly important statement. To understand it better, we look in more detail at how
methods are invoked. This procedure is known as method lookup , method binding , or method
dispatch. We will use the term “method lookup” in this topic.
We start with a simple method-lookup scenario. Assume that we have an object of a class
PhotoPost stored in a variable v1 declared of type PhotoPost (Figure 9.5). The PhotoPost
class has a display method and no declared superclass. This is a very simple situation—there
is no inheritance or polymorphism involved here. We then execute the statement
Figure 9.5
Method lookup with
a simple object
instance of
When this statement executes, the display method is invoked in the following steps:
The variable v1 is accessed.
The object stored in that variable is found (following the reference).
Search WWH ::

Custom Search