Java Reference
In-Depth Information
Vehicle
Car
Boat
Plane
FIGURE 9.6 A vehicle class hierarchy
automatically have that variable because of inheritance. Any change we make to the
representation of the speed of a vehicle is automatically reflected in all descendant
classes. Similarly, we may declare an abstract method called fuelConsumption ,
whose purpose is to calculate how quickly fuel is being consumed by a particular
vehicle. The details of the fuelConsumption method must be defined by each type of
vehicle, but the Vehicle class establishes that all vehicles consume fuel and provides
a consistent way to compute that value.
Some concepts don't apply to all vehicles, so we wouldn't represent those
concepts at the Vehicle level. For instance, we wouldn't include a variable called
numberOfWheels in the Vehicle class, because not all vehicles have wheels. The
child classes for which wheels are appropriate can add that concept at the appro-
priate level in the hierarchy.
There are no restrictions as to where in a class hierarchy an abstract class
can be defined. Usually they are located at the upper levels of a class hierarchy.
However, it is possible to derive an abstract class from a nonabstract parent.
Usually, a child of an abstract class will provide a specific definition for an
abstract method inherited from its parent. Note that this is just a specific case of
overriding a method, giving a different definition than the one the
parent provides. If a child of an abstract class does not give a defini-
tion for every abstract method that it inherits from its parent, then
the child class is also considered abstract.
Note that it would be a contradiction for an abstract method to
be modified as final or static . Because a final method cannot be
overridden in subclasses, an abstract final method would have no
way of being given a definition in subclasses. A static method can be invoked
using the class name without declaring an object of the class. Because abstract
methods have no implementation, an abstract static method would make no sense.
Choosing which classes and methods to make abstract is an important part
of the design process. You should make such choices only after careful consider-
ation. By using abstract classes wisely, you can create flexible, extensible software
designs.
KEY CONCEPT
A class derived from an abstract par-
ent must override all of its parent's
abstract methods, or the derived class
will also be considered abstract.
 
Search WWH ::




Custom Search