Java Reference
In-Depth Information
Code 8.5
Source code of the
NewsFeed class
(second version)
* Construct an empty news feed.
public NewsFeed()
posts = new ArrayList<Post>();
* Add a post to the news feed.
* @param post The post to be added.
public void addPost(Post post)
* Show the news feed. Currently: print the news feed details
* to the terminal. (To do: replace this later with display
* in web browser.)
public void show()
// display all posts
for (Post post : posts) {
System.out.println(); // empty line between posts
As we can see, the code has become significantly shorter and simpler since our change to use
inheritance. Where in the first version (Code 8.3) everything had to be done twice, it now ex-
ists only once. We have only one collection, only one method to add posts, and one loop in the
show method.
The reason why we could shorten the source code is that, in the new version, we can use the
type Post where we previously used MessagePost and PhotoPost . We investigate this first
by examining the addPost method.
In our first version, we had two methods to add posts to the news feed. They had the following
public void addMessagePost(MessagePost message)
public void addPhotoPost(PhotoPost photo)
Search WWH ::

Custom Search