Java Reference
In-Depth Information
This shows just three classes in a hierarchy, but there can be as many as you like.
Let's consider a more concrete example. You could define a class
Dog
that could represent a dog of any
kind:
class Dog {
// Members of the Dog class...
}
This might contain a data member identifying the name of a particular dog, such as
Lassie
or
Poochy
,
and another data member to identify the breed, such as
Border Collie
or
Pyrenean Mountain Dog
. From the
Dog
class, you could derive a
Spaniel
class that represented dogs that were spaniels:
class Spaniel extends Dog {
// Members of the Spaniel class...
}
The
extends
keyword that you use here identifies that
Dog
is a base class for
Spaniel
, so an object of
type
Spaniel
has members that are inherited from the
Dog
class, in addition to the members of the
Span-
iel
class that appear in its definition. The breed is
Spaniel
for all instances of the class
Spaniel
, although
in general the name for each spaniel may be different. The
Spaniel
class might have some additional data
members that characterize the specifics of what it means to be a spaniel. You see in a moment how you can
arrange for the base class data members to be set appropriately.
A
Spaniel
object is a specialized instance of a
Dog
object. This reflects real life. A spaniel is obviously a
dog and has all the properties of a basic dog, but it has some unique characteristics of its own that distinguish
it from all the dogs that are not spaniels. The inheritance mechanism that adds all the properties of the base
class —
Dog
in this instance — to those in the derived class is a good model for the real world. The members
of the derived class define the properties that differentiate it from the base type, so when you derive one
class from another, you can think of your derived class as a specification for objects that are specializations