Java Reference
In-Depth Information
You should now have a situation corresponding to Figure 9.4, with
display
methods in three
classes. Compile your project. (If there are errors, remove them. This design should work.)
Before executing, predict which of the
display
methods will get called if you execute the
news feed's
show
method.
Try it out. Enter a message post and a photo post into the news feed and call the news feed's
show
method. Which
display
methods were executed? Was your prediction correct? Try to
explain your observations.
Figure 9.4
Display, version 3:
display
method
in subclasses and
superclass
NewsFeed
Post
GLVSOD\
MessagePost
PhotoPost
GLVSOD\
GLVSOD\
9.3
Overriding
The next design we shall discuss is one where both the superclass and the subclasses have a
display
method (Figure 9.4). The header of all the
display
methods is exactly the same.
Code 9.1 shows the relevant details of the source code of all three classes. Class
Post
has a
display
method that prints out all the fields that are declared in
Post
(those common to mes-
sage posts and photo posts), and the subclasses
MessagePost
and
PhotoPost
print out the
fields specific to
MessagePost
and
PhotoPost
objects, respectively.
Code 9.1
Source code of the
display
methods
in all three classes
public
class
Post
{
...
public
void
display()
{
System.out.println(username);
System.out.print(timeString(timestamp));
Search WWH ::
Custom Search