Java Reference
In-Depth Information
Exercise 9.1 Open your last version of the network project. (You can use network-v2 if you
do not have your own version yet.) Remove the display method from class Post and move
it into the MessagePost and PhotoPost classes. Compile. What do you observe?
When we try to move the display method from Post to the subclasses, we notice that we
have some problems: the project does not compile any more. There are two fundamental issues:
We get errors in the MessagePost and PhotoPost classes, because we cannot access the
superclass fields.
We get an error in the NewsFeed class, because it cannot find the display method.
The reason for the first sort of error is that the fields in Post have private access and so are
inaccessible to any other class—including subclasses. Because we do not wish to break encap-
sulation and make these fields public, as was suggested above, the easiest way to solve this is to
define public accessor methods for them. However, in Section 9.9, we shall introduce a further
type of access designed specifically to support the superclass-subclass relationship.
The reason for the second sort of error requires a more detailed explanation, and this is explored
in the next section.
Calling display from NewsFeed
First, we investigate the problem of calling the display method from NewsFeed . The relevant
lines of code in the NewsFeed class are:
for(Post post : posts) {
The for-each statement retrieves each post from the collection; the first statement inside its
body tries to invoke the display method on the post. The compiler informs us that it cannot
find a display method for the post.
On the one hand, this seems logical; Post does not have a display method any more (see Figure 9.2).
On the other hand, it seems illogical and is annoying. We know that every Post object in
the collection is in fact a MessagePost or a PhotoPost object, and both have display
methods. This should mean that post.display() ought to work, because, whatever it is—
MessagePost or PhotoPost —we know that it does have a display method.
To understand in detail why it doesn't work, we need to look more closely at types. Consider
the following statement:
Car c1 = new Car();
We say that the type of c1 is Car . Before we encountered inheritance, there was no need to
distinguish whether by “type of c1 ” we meant “the type of the variable c1 ” or “the type of the
object stored in c1 .” It did not matter, because the type of the variable and the type of the object
were always the same.
Search WWH ::

Custom Search