Java Reference
In-Depth Information
Creating a Class Hierarchy
If you're creating a large set of classes, it makes sense for your classes to inherit from
the existing class hierarchy and to make up a hierarchy themselves for these advantages:
Functionality common to multiple classes can be put into a superclass, which
enables it to be used repeatedly in all classes below it in the hierarchy.
n
Changes to a superclass automatically are reflected in all its subclasses, their sub-
classes, and so on. There is no need to change or recompile any of the lower
classes; they receive the new information through inheritance.
n
For example, imagine that you have created a Java class to implement all the features of
a volcanic exploratory robot. (This shouldn't take much imagination.)
The VolcanoRobot class is completed and works successfully. Now you want to create a
Java class called MarsRobot .
These two kinds of robots have similar features—both are research robots that work in
hostile environments and conduct research. Your first impulse might be to open up the
VolcanoRobot.java source file and copy a lot of it into a new source file called
MarsRobot.java .
A better plan is to figure out the common functionality of MarsRobot and VolcanoRobot
and organize it into a more general class hierarchy. This might be a lot of work just for
the classes VolcanoRobot and MarsRobot , but what if you also want to add MoonRobot ,
UnderseaRobot , and DesertRobot? Factoring common behavior into one or more
reusable superclasses significantly reduces the overall amount of work that must be done.
To design a class hierarchy that might serve this purpose, start at the top with the class
Object , the pinnacle of all Java classes. The most general class to which these robots
belong might be called Robot . A robot, generally, could be defined as a self-controlled
exploration device. In the Robot class, you define only the behavior that qualifies some-
thing to be a device, self-controlled, and designed for exploration.
There could be two classes below Robot : WalkingRobot and DrivingRobot . The obvious
thing that differentiates these classes is that one travels by foot and the other by wheel.
The behavior of walking robots might include bending over to pick up something, duck-
ing, running, and the like. Driving robots would behave differently. Figure 1.3 shows
what you have so far.
Search WWH ::




Custom Search