Java Reference
In-Depth Information
The purpose of using inheritance is now fairly obvious. Instances of class MessagePost will
have all fields defined in class MessagePost and in class Post . ( MessagePost inherits the
fields from Post .) Instances of PhotoPost will have all fields defined in PhotoPost and in
Post . Thus, we achieve the same as before, but we need to define the fields username , time-
stamp , likes , and comments only once, while being able to use them in two different places).
The same holds true for methods: instances of subclasses have all methods defined in both
the superclass and the subclass. In general, we can say: because a message post is a post, a
message-post object has everything that a post has, and more. And because a photo post is also
a post, it has everything that a post has, and more.
Thus, inheritance allows us to create two classes that are quite similar, while avoiding the need
to write the identical part twice. Inheritance has a number of other advantages, which we dis-
cuss below. First, however, we will take another, more general look at inheritance hierarchies.
8.3
Inheritance hierarchies
Inheritance can be used much more generally than shown in the example above. More than two
subclasses can inherit from the same superclass, and a subclass can, in turn, be a superclass to
other subclasses. The classes then form an inheritance hierarchy.
Concept:
Classes that are
linked through inher-
itance relationships
form an inherit-
ance hierarchy .
The best-known example of an inheritance hierarchy is probably the classification of species
used by biologists. A small part is shown in Figure 8.6. We can see that a poodle is a dog, which
is a mammal, which is an animal.
We know some things about poodles—for example, that they are alive, they can bark, they eat
meat, and they give birth to live young. On closer inspection, we see that we know some of
these things not because they are poodles, but because they are dogs, mammals, or animals.
An instance of class Poodle (an actual poodle) has all the characteristics of a poodle, a dog, a
mammal, and an animal, because a poodle is a dog, which is a mammal, and so on.
Figure 8.6
An example of an
inheritance hierarchy
 
 
Search WWH ::




Custom Search