Java Reference
In-Depth Information
3.10. Extending Classes: How and When
The ability to write extended classes is a large part of the benefits of
object-oriented programming. When you extend a class to add new func-
tionality, you create what is commonly termed an IsA relationshipthe ex-
tension creates a new kind of object that "is a" kind of the original class.
The IsA relationship is quite different from a HasA relationship, in which
one object uses another object to store state or do workit "has a" refer-
ence to that other object.
Let's look at an example. Consider a Point class that represents a point in
two-dimensional space by an ( x, y ) pair. You might extend Point to cre-
ate, say, a Pixel class to represent a colored point on a screen. A Pixel
IsA Point : anything that is true of a simple Point would also be true of
a Pixel . The Pixel class might add mechanisms to represent the color of
the pixel or a reference to an object that represents the screen on which
the pixel is drawn. As a point in a two-dimensional space (the plane of a
display) with an extension to the contract (it has color and a screen), a
Pixel IsA Point .
On the other hand, a circle is not a point. Although a circle can be de-
scribed by a point and a radius, a point has uses that no circle would
have. For example, if you had a method to place the center of a rectangle
at a particular point, would it really make sense to pass in a circle? A
circle HasA center that IsA point, but a circle Is Not A point with a radius,
and therefore should not be a subclass of Point .
There are times when the correct choice is not obvious and for which dif-
ferent choices will be correct depending on the application. In the end,
applications must run and make sense.
Getting IsA versus HasA relationships correct is both subtle and poten-
tially critical. For example, one obvious and common way to design an
employee database using object-oriented tools is to use an Employee class
that has the properties all persons share (such as name and employee
number) and extend it to classes for particular kinds of employees, such
as Manager , Engineer , and FileClerk .
 
Search WWH ::




Custom Search