Main Page

Inheritance in Action

A truly object-oriented language must support inheritance, the capability of a class to reuse
) methods and properties from another class. In the previous chapter, you learned how to
define properties and methods of a class, but what if you want two classes to use the same meth-
ods? This is where inheritance comes in.
Inheritance in Action
The easiest way to describe inheritance is through a classic example, geometric shapes. There are
really two types of shapes: ellipses (which are rounded) and polygons (which have a certain num-
ber of sides). Circles are a type of ellipse with one focus; triangles, rectangles, and pentagons are
types of polygons with a different number of sides. A square is a type of rectangle with all sides
equal. This describes a perfect inheritance relationship.
In this example, Shape is the
base class
(the class to be inherited from) of Ellipse and Polygon. An
Ellipse has one property called
, indicating the number of foci the Ellipse has. Circle inherits
from Ellipse, so Circle is a
of Ellipse and Ellipse is a
of Circle. Likewise, Triangle,
Rectangle, and Pentagon are subclasses of Polygon and Polygon is a superclass to each of these
shapes. Finally, Square inherits from Rectangle.
The inheritance relationship is best explained through diagrams, which is where the Universal
Modeling Language (UML) comes in. One of UML’s many purposes is to visually represent com-
plex object relationships such as inheritance. Figure 4-1 is a UML diagram explaining the relation-
ship of Shape to its subclasses:
07_579088 ch04.qxd 3/28/05 11:36 AM Page 103

JavaScript EditorFree JavaScript Editor     Ajax Editor