Java Reference
In-Depth Information
call this class Post . Then we can declare that a MessagePost is a Post and a PhotoPost is a
Post . Finally, we add those extra details needed for a message post to the MessagePost class,
and those for a photo post to the PhotoPost class. The essential feature of this technique is that
we need to describe the common features only once.
Inheritance allows
us to define one
class as an exten-
sion of another.
Figure 8.5 shows a class diagram for this new structure. At the top, it shows the class Post ,
which defines all fields and methods that are common to all posts (messages and photos).
Below the Post class, it shows the MessagePost and PhotoPost classes, which hold only
those fields and methods that are unique to each particular class.
Figure 8.5
MessagePost and
PhotoPost inheriting
from Post
This new feature of object-oriented programming requires some new terminology. In a situ-
ation such as this one, we say that the class MessagePost inherits from class Post . Class
PhotoPost also inherits from Post . In the vernacular of Java programs, the expression “class
MessagePost extends class Post ” could be used, because Java uses an extends keyword to
define the inheritance relationship (as we shall see shortly). The arrows in the class diagram
(usually drawn with hollow arrow heads) represent the inheritance relationship.
A superclass is
a class that is ex-
tended by another
Class Post (the class that the others inherit from) is called the parent class or superclass. The
inheriting classes ( MessagePost and PhotoPost in this example) are referred to as child
classes or subclasses. In this topic, we will use the terms “superclass” and “subclass” to refer to
the classes in an inheritance relationship.
A subclass is a
class that extends
(inherits from) another
class. It inherits all
fields and methods
from its superclass.
Inheritance is sometimes also called an is-a relationship. The reason is that a subclass is a spe-
cialization of a superclass. We can say that “a message post is a post” and “a photo post is a post.”
Search WWH ::

Custom Search