Java Reference
In-Depth Information
The class of the object is found (following the “instance of” reference).
4 The implementation of the display method is found in the class and executed.
This is all very straightforward and not surprising.
Next, we look at method lookup with inheritance. This scenario is similar, but this time the PhotoPost
class has a superclass Post and the display method is defined only in the superclass (Figure 9.6).
Figure 9.6
Method lookup
with inheritance
instance of
We execute the same statement. The method invocation then starts in a similar way: steps 1 to 3
from the previous scenario are executed again, but then it continues differently:
4No display method is found in class PhotoPost .
Because no matching method was found, the superclass is searched for a matching method.
If no method is found in the superclass, the next superclass (if it exists) is searched. This
continues all the way up the inheritance hierarchy to the Object class, until a method is
found. Note that at runtime a matching method should definitely be found, or else the class
would not have compiled.
6 In our example, the display method is found in class Post , and will be executed.
This scenario illustrates how objects inherit methods. Any method found in a superclass can be
invoked on a subclass object and will correctly be found and executed.
Next, we come to the most interesting scenario: method lookup with a polymorphic variable
and method overriding (Figure 9.7). The scenario is again similar to the one before, but there
are two changes:
The declared type of the variable v1 is now Post , not PhotoPost .
The display method is defined in class Post and then redefined (overridden) in class
PhotoPost .
Search WWH ::

Custom Search