Java Reference
In-Depth Information
Table 9.7
Method Output for Class G
G
toString
G
method1
G 1
method2
G 2
The next class in the hierarchy is F , which extends G . The method1 is not overrid-
den, so its output is " G 1 " as it was in the superclass. F does override toString to
return " F " . It also overrides method2 to print " F 2 " and then call the superclass's
( G 's) version of method2 . When there is a call to a superclass's method, we can evalu-
ate its output immediately and put it into our table by looking at the superclass. This
means that the F class's method2 prints " F 2 G 2 " . Table 9.8 shows this information.
Table 9.8
Method Output for Classes F and G
F
G
toString
F
G
method1
G 1
G 1
method2
F 2 G 2
G 2
The next class to tackle is E , which extends F . It does not override method1 or
toString , so these methods produce the same output as they do in superclass F .
Class E does override method2 to print " E 2 " and then call method1 . Since
method1 prints " G 1 " , calling method2 on an E object prints " E 2 G 1 " .
But here's where things get tricky: You shouldn't write this output in your table.
The reason will become clear when we look at the H class, which is a subclass of E
that overrides method1 . Because of polymorphism, if you call method2 on an H
object, when it makes the inner call to method1 , it will use the version from the H
class. What you should write into your table for E 's method2 output is that it prints
" E 2 " and then calls method1 . Table 9.9 shows the information for class E .
Table 9.9
Method Output for Classes E , F , and G
E
F
G
toString
F
F
G
method1
G 1
G 1
G 1
method2
E 2 method1()
F 2 G 2
G 2
Lastly we will examine class H , which extends E . It does not override toString ,
so it produces the same output as in superclass E . It overrides only method1 to print
" H 1 " . These methods are simple (they don't call any others), so we can write the
toString and method1 output into the table immediately.
 
Search WWH ::




Custom Search