Java Reference
In-Depth Information
t1 = s1;
s1 = phd1;
phd1 = s1;
Exercise 8.13 Test your answers to the previous question by creating bare-bones versions
of the classes mentioned in that exercise and trying it out in BlueJ.
8.7.3
Subtyping and parameter passing
Passing a parameter (that is, assigning an actual parameter to a formal parameter variable) be-
haves in exactly the same way as an assignment to a variable. This is why we can pass an object
of type MessagePost to a method that has a parameter of type Post . We have the following
definition of the addPost method in class NewsFeed :
public class NewsFeed
{
public void addPost(Post post)
{
. . .
}
}
We can now use this method to add message posts and photo posts to the feed:
NewsFeed feed = new NewsFeed();
MessagePost message = new MessagePost(...);
PhotoPost photo = new PhotoPost(...);
feed.addPost(message);
feed.addPost(photo);
Because of subtyping rules, we need only one method (with a parameter of type Post ) to add
both MessagePost and PhotoPost objects.
We will discuss subtyping in more detail in the next chapter.
8.7.4
Polymorphic variables
Variables holding object types in Java are polymorphic variables. The term “polymorphic”
(literally, many shapes ) refers to the fact that a variable can hold objects of different types
(namely, the declared type or any subtype of the declared type). Polymorphism appears in
object-oriented languages in several contexts—polymorphic variables are just the first example.
We will discuss other incarnations of polymorphism in more detail in the next chapter.
For now, we just observe how the use of a polymorphic variable helps us simplify our show
method. The body of this method is
for(Post post : posts) {
post.display();
System.out.println(); // empty line between posts
}
 
Search WWH ::




Custom Search