
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
208
|
Chapter 6: Inheritance
Inheritance Versus Composition
In this chapter, we focused most of our attention on one type of interobject relation-
ship: inheritance. But inheritance isn’t the only game in town. Composition, an alter-
native form of interobject relationship, often rivals inheritance as an OOP design
technique. In composition, one class (the front end class) stores an instance of
another class (the back end class) in an instance property. The front end class dele-
gates work to the back end class by invoking methods on that instance. Here’s the
basic approach, shown in code:
// The back end class is analogous to the superclass in inheritance.
class BackEnd {
public function doSomething ( ) {
}
}
// The front end class is analogous to the subclass in inheritance.
class FrontEnd {
// An instance of the back end class is stored in
// a private instance property, in this case called be.
private var be:BackEnd;
// The constructor creates the instance of the back end class.
public function FrontEnd ( ) {
be = new BackEnd( );
}
// This method delegates work to BackEnd.doSomething( ).
public function doSomething ( ) {
be.doSomething( );
}
}
Notice that the FrontEnd class does not extend the BackEnd class. Composition does
not require or use its own special syntax, as inheritance ...