Java Reference
In-Depth Information
Where do qualities such as status, temperature, or speed come in? At the place they fit
into the class hierarchy most naturally. Because all robots have a need to keep track of
the temperature of their environment, it makes sense to define temperature as an
instance variable in Robot . All subclasses would have that instance variable as well.
Remember that you need to define a behavior or attribute only once in the hierarchy, and
it automatically is inherited by each subclass.
NOTE
Designing an effective class hierarchy involves a lot of planning
and revision. As you attempt to put attributes and behavior into a
hierarchy, you're likely to find reasons to move some classes to
different spots in the hierarchy. The goal is to reduce the number
of repetitive features that are needed.
Inheritance in Action
Inheritance in Java works much more simply than it does in the real world. There are no
executors of a will or courts of any kind required in Java.
When you create a new object, Java keeps track of each variable defined for that object
and each variable defined for each superclass of the object. In this way, all the classes
combine to form a template for the current object, and each object fills in the information
appropriate to its situation.
Methods operate similarly: A new object has access to all method names of its class and
superclass. This is determined dynamically when a method is used in a running program.
If you call a method of a particular object, the Java interpreter first checks the object's
class for that method. If the method isn't found, the interpreter looks for it in the super-
class of that class, and so on, until the method definition is found. This is illustrated in
Figure 1.5.
Things get complicated when a subclass defines a method that matches a method defined
in a superclass in name and other aspects. In this case, the method definition found first
(starting at the bottom of the hierarchy and working upward) is the one that is used.
Because of this, you can create a method in a subclass that prevents a method in a super-
class from being used. To do this, you give the method with the same name, return type,
and arguments as the method in the superclass. This procedure is called overriding (see
Figure 1.6).
Search WWH ::




Custom Search