Java Reference
In-Depth Information
Figure 7-1
A conceptual depiction of the
Triangle
class
Even though
TwoDShape
is a superclass for
Triangle
, it is also a completely independ-
ent, stand-alone class. Being a superclass for a subclass does not mean that the superclass
cannot be used by itself. For example, the following is perfectly valid:
Of course, an object of
TwoDShape
has no knowledge of or access to any subclasses of
TwoDShape
.
The general form of a
class
declaration that inherits a superclass is shown here:
You can specify only one superclass for any subclass that you create. Java does not support
the inheritance of multiple superclasses into a single subclass. (This differs from C++, in
which you can inherit multiple base classes. Be aware of this when converting C++ code
to Java.) You can, however, create a hierarchy of inheritance in which a subclass becomes
a superclass of another subclass. Of course, no class can be a superclass of itself.
A major advantage of inheritance is that once you have created a superclass that defines
the attributes common to a set of objects, it can be used to create any number of more spe-
cific subclasses. Each subclass can precisely tailor its own classification. For example, here
is another subclass of
TwoDShape
that encapsulates rectangles: