Java Reference
In-Depth Information
achieve this, we can now define a new subclass of Post named EventPost (Figure 8.7). Because
EventPost is a subclass of Post , it automatically inherits all fields and methods that we have
already defined in Post . Thus, EventPost objects already have a username, a time stamp, a likes
counter, and comments. We can then concentrate on adding attributes that are specific to event
posts, such as the event type. The event type might be stored as an enumeration constant (see
Chapter 6) or as a string describing the event.
Figure 8.7
Network items with an
EventPost class
This is an example of how inheritance enables us to reuse existing work. We can reuse the code
that we have written for photo posts and message posts (in the Post class) so that it also works
for the EventPost class. The ability to reuse existing software components is one of the great
benefits that we get from the inheritance facility. We will discuss this in more detail later.
Inheritance al-
lows us to reuse
previously written
classes in a new
This reuse has the effect that a lot less new code is needed when we now introduce additional
post types. Because new post types can be defined as subclasses of Post , only the code that is
actually different from Post has to be added.
Now imagine that we change the requirements a bit: event posts in our network application
will not have a “Like” button or comments attached. They are for information only. How do we
achieve this? Currently, because EventPost is a subclass of Post , it automatically inherits the
likes and comments fields. Is this a problem?
We could leave everything as it is and decide to never display the likes count or comments
for event posts—just ignore the fields. This does not feel right. Having the fields present but
unused invites problems. Someday a maintenance programmer will come along who does not
realize that these fields should not be used and try to process them.
Or we could write EventPost without inheriting from Post . But then we are back to code
duplication for the username and timestamp fields and their methods.
The solution is to refactor the class hierarchy. We can introduce a new superclass for all posts that
have comments attached (named CommentedPost ), which is a subclass of Post (Figure 8.8). We
then shift the likes and comments fields from the Post class to this new class. MessagePost
and PhotoPost are now subclasses of our new CommentedPost class, while EventPost
Search WWH ::

Custom Search