Java Reference
In-Depth Information
Code reuse Existing code can be reused. If a class similar to the one we need already exists,
we can sometimes subclass the existing class and reuse some of the existing code rather than
having to implement everything again.
Easier maintenance Maintaining the application becomes easier, because the relationship
between the classes is clearly expressed. A change to a field or a method that is shared be-
tween different types of subclasses needs to be made only once.
Extendibility Using inheritance, it becomes much easier to extend an existing application in
certain ways.
Exercise 8.9 Order these items into an inheritance hierarchy: apple, ice cream, bread, fruit,
food item, cereal, orange, dessert, chocolate mousse, baguette.
Exercise 8.10 In what inheritance relationship might a touch pad and a mouse be? (We are
talking about computer input devices here, not small furry mammals.)
Exercise 8.11 Sometimes things are more difficult than they first seem. Consider this: In what
kind of inheritance relationship are Rectangle and Square ? What are the arguments? Discuss.
8.7
Subtyping
The one thing we have not yet investigated is how the code in the NewsFeed class was changed
when we modified our project to use inheritance. Code 8.5 shows the full source code of class
NewsFeed . We can compare this with the original source shown in Code 8.3.
Code 8.5
Source code of the
NewsFeed class
(second version)
import java.util.ArrayList;
/**
* The NewsFeed class stores news posts for the news feed in a
* social-network application (like FaceBook or Google+).
*
* Display of the posts is currently simulated by printing the
* details to the terminal. (Later, this should display in a browser.)
*
* This version does not save the data to disk, and it does not
* provide any search or ordering functions.
*
* @author Michael Kölling and David J. Barnes
* @version 0.2
*/
public class NewsFeed
{
private ArrayList<Post> posts;
 
 
Search WWH ::




Custom Search