Java Reference
In-Depth Information
Exercise 9.7 Having to use a superclass call in display is somewhat restrictive in the ways in
which we can format the output, because it is dependent on the way the superclass formats its fields.
Make any necessary changes to the Post class and to the display method of MessagePost so
that it produces the output shown in Figure 9.11. Any changes you make to the Post class should
be visible only to its subclasses. Hint: You could add protected accessors to do this.
Figure 9.11
Output from display
mixing subclass and
superclass details
(shaded areas represent
superclass details)
Leonardo da Vinci
Had a great idea this morning.
But now I forgot what it was. Something to do with flying...
40 seconds ago - 2 people like this.
No comments.
The instanceof operator
One of the consequences of the introduction of inheritance into the network project has been
that the NewsFeed class knows only about Post objects and cannot distinguish between
message posts and photo posts. This has allowed all types of post to be stored in a single list.
However, suppose that we wish to retrieve just the message posts or just the photo posts from
the list; how would we do that? Or perhaps we wish to look for a message by a particular
author? That is not a problem if the Post class defines a getAuthor method, but this will find
both message and photo posts. Will it matter which type is returned?
There are occasions when we need to rediscover the distinctive dynamic type of an object rather
than dealing with a shared supertype. For this, Java provides the instanceof operator. The
instanceof operator tests whether a given object is, directly or indirectly, an instance of a
given class. The test
obj instanceof MyClass
returns true if the dynamic type of obj is MyClass or any subclass of MyClass . The left
operand is always an object reference, and the right operand is always the name of a class. So
post instanceof MessagePost
returns true only if post is a MessagePost , as opposed to a PhotoPost , for instance.
Use of the instanceof operator is often followed immediately by a cast of the object refer-
ence to the identified type. For instance, here is some code to identify all of the message posts
in a list of posts and to store them in a separate list.
ArrayList<MessagePost> messages = new ArrayList<MessagePost>();
for(Post post : posts) {
if(post instanceof MessagePost) {
messages.add((MessagePost) post);
It should be clear that the cast here does not alter the post object in any way, because we have
just established that it already is a MessagePost object.
Search WWH ::

Custom Search