ptg7068951
Building an Inheritance Hierarchy 125
To make this modem display its speed by calling the displaySpeed()
method, you call the method:
device.displaySpeed();
The Modemobject named devicewould respond to this statement by dis-
playing the text “Speed: 28800.”
Understanding Inheritance
A big advantage to OOPis inheritance, which enables one object to inherit
behavior and attributes from another object.
When you start creating objects, you sometimes find that a new object you
want is a lot like an object you already have.
What if David Lightman wanted an object that could handle error correc-
tion and other advanced modem features that weren’t around in 1983
when WarGameswas released? Lightman could create a new
ErrorCorrectionModemobject by copying the statements of the Modem
object and revising them. However, if most of the behavior and attributes
of ErrorCorrectionModemare the same as those of Modem, this is a lot of
unnecessary work. It also means that Lightman would have two separate
programs to update if something needed to be changed later.
Through inheritance, a programmer can create a new class of objects by
defining how they are different than an existing class. Lightman could
make ErrorCorrectionModeminherit from Modem, and all he would need to
write are things that make error-correction modems different than modems.
A class of objects inherits from another class by using the extendsstate-
ment. The following is a skeleton of an ErrorCorrectionModemclass that
inherits from the Modemclass:
public classErrorCorrectionModem extendsModem {
// program goes here
}
Building an Inheritance Hierarchy
Inheritance, which enables a variety of related classes to be developed with-
out redundant work, makes it possible for code to be passed down from
one class to another class to another class. This grouping of classes is called