You may be thinking that one accelerate() method might not work for all instances of the class
Automobile. May be the acceleration behavior a Ferrari should be modeled differently from the acceleration
behavior of a Kia. If we want to model such differences, we can take advantage of the OO programming
paradigm called inheritance.
One class can inherit from another, in which case the new class (called the subclass or subordinant class
or child class) carries all the variables and methods of the higher-level class (called the superclass or superior
class or parent class). In addition, the child class can add state variables unique to the child class, and add
behavior methods unique to the child class. In addition, the child class can override methods of the parent class
in order to give the child class different behavior, even though the name of the method implementing the behavior
has the same name as the method of the parent class.
These sorts of considerations lead software developers to create a class hierarchy. The programmer defines
the more general state variables and behavior methods in higher-level classes. Then, when writing the subordinant
classes, the programmer uses the inherited state and behavior when it fits, and adds state variables, methods,
and overriding methods to subordinant classes in order to implement differences between the superior and
subordinant classes.
The beauty of this technique is that classes which are written and tested do not change. Existing software
functionality can be reused. When the programmer requires new features in a class, the programmer can inherit
from an existing, tested class, and write new software simply to meet the new requirements.
If one decides to implement the accelerate() method differently for different Automobiles, one
would write the parent class Automobile, and then have subordinant classes inherit from Automobile.
In our example, we might design several classes to inherit from Automobile, a class called EconomyCar,
a class called FamilyCar, and a class called SportsCar. Each of these subordinant classes would inherit
the accelerate() method from the Automobile class, and could override the inherited accelerate()
method to change the acceleration behavior of instances of the subordinant class. If a subordinant class does not
override the method of the superior class, instances of the subordinant class will respond to the method just as
instances of the superior class do. If my Ford “is” a FamilyCar, my Ford also “is” an Automobile, because
FamilyCar inherits from Automobile.
No comments:
Post a Comment