Java Reference
In-Depth Information
Post
class and that of the
PhotoPost
class being executed for the same object. Then all the
details would be printed out. (A different solution will be discussed later in this chapter.)
This is, in fact, quite easy to achieve. We can simply use the
super
construct, which we have
already encountered in the context of constructors in Chapter 8. Code 9.2 illustrates this idea
with the
display
method of the
PhotoPost
class.
Code 9.2
Redefining method
with
super
call
public
void
display()
{
super
.display();
System.out.println(
" ["
+ filename +
"]"
);
System.out.println(
" "
+ caption);
}
When
display
is now called on a
PhotoPost
object, initially the
display
method in the
PhotoPost
class will be invoked. As its first statement, this method will in turn invoke the
display
method of the superclass, which prints out the general post information. When con-
trol returns from the superclass method, the remaining statements of the subclass method print
the distinctive fields of the
PhotoPost
class.
There are three details worth noting:
■
Contrary to the case of
super
calls in constructors, the method name of the superclass
method is explicitly stated. A
super
call in a method always has the form
super.
method-name
(
parameters
)
The parameter list can, of course, be empty.
■
Again, contrary to the rule for
super
calls in constructors, the
super
call in methods may
occur anywhere within that method. It does not have to be the first statement.
■
And contrary to the case of
super
calls in constructors, no automatic
super
call is gener-
ated and no
super
call is required; it is entirely optional. So the default behavior gives the
effect of a subclass method completely hiding (i.e., overriding) the superclass version of the
same method.
Exercise 9.3
Modify your latest version of the
network
project to include the super call in the
display
method. Test it. Does it behave as expected? Do you see any problems with this solution?
It is worth reiterating what was illustrated in Exercise 8.6: that in the absence of method over-
riding, the non-private members of a superclass are directly accessible from its subclasses
without any special syntax. A
super
call only has to be made when it is necessary to access the
superclass version of an
overridden
method.
If you completed Exercise 9.3, you will have noticed that this solution works but is not perfect
yet. It prints out all details, but in a different order from what we wanted. We will fix this last
problem later in the chapter.
Search WWH ::
Custom Search