Java Reference
In-Depth Information
1.11. Extending a Class
One of the major benefits of object orientation is the ability to extend,
or subclass, the behavior of an existing class and continue to use code
written for the original class when acting on an instance of the subclass.
The original class is known as the superclass. When you extend a class to
create a new class, the new extended class inherits fields and methods
of the superclass.
If the subclass does not specifically override the behavior of the super-
class, the subclass inherits all the behavior of its superclass because it
inherits the fields and methods of its superclass. In addition, the subclass
can add new fields and methods and so add new behavior.
Consider the Walkman example. The original model had a single jack for
one person to listen to the tape. Later models incorporated two jacks so
two people could listen to the same tape. In the object-oriented world,
the two-jack model extends, or is a subclass of, the basic one-jack mod-
el. The two-jack model inherits the characteristics and behavior of the
basic model and adds new behavior of its own.
Customers told Sony they wanted to talk to each other while sharing a
tape in the two-jack model. Sony enhanced the two-jack model to include
two-way communications so people could chat while listening to music.
The two-way communications model is a subclass of the two-jack model,
inherits all its behavior, and again adds new behavior.
Sony created many other Walkman models. Later models extend the cap-
abilities of the basic modelthey subclass the basic model and inherit fea-
tures and behavior from it.
Let's look at an example of extending a class. Here we extend our former
Point class to represent a pixel that might be shown on a screen. The
new Pixel class requires a color in addition to x and y coordinates:
class Pixel extends Point {
Color color;
 
Search WWH ::




Custom Search