Java Reference
In-Depth Information
FIGURE 1.2
A class hierarchy.
Class A
• Class A is the superclass of B
• Class B is a subclass of A
• Class B is the superclass
of C, D, and E
• Classes C, D, and E
are subclasses of B
1
Class B
Class C
Class D
Class E
Each class farther down the hierarchy becomes more tailored to a specific purpose. A
class hierarchy defines abstract concepts at the top of the hierarchy. Those concepts
become more concrete farther down the line of subclasses.
Often when you create a new class in Java, you want all the functionality of an existing
class with some modifications of your own creation. For example, you might want a ver-
sion of
CommandButton
that makes a sound when clicked.
To receive all the
CommandButton
functionality without doing any work to re-create it,
you can define your class as a subclass of
CommandButton
. Your class then automatically
would inherit behavior and attributes defined in
CommandButton
as well as the behavior
and attributes defined in the superclasses of
CommandButton
. All you have to worry about
are the things that make your new class different from
CommandButton
itself. Subclassing
is the mechanism for defining new classes as the differences between those classes and
their superclass.
Subclassing
is the creation of a new class that inherits from an existing class. The only
task in the subclass is to indicate the differences in behavior and attributes between itself
and its superclass.
If your class defines entirely new behavior and isn't a subclass of another class, you can
inherit directly from the
Object
class. This allows it to fit into the Java class hierarchy. If
you create a class definition that doesn't indicate a superclass, Java assumes that the new
class is inheriting directly from
Object
. The
VolcanoRobot
class you created earlier
today did not specify a superclass, so it's a subclass of the
Object
class.