Friday, February 09, 2007

Inheritance vs. Composition

Two fundamental ways to relate classes are inheritance and composition. With inheritance, a superclass Fruit may have a subclass Apple.

Using composition, Apple would have an instance variable that references a Fruit object.

Inheritance has the benefits of dynamic binding whereby the appropriate method implementation is automatically invoked at runtime based on the class of the object and polymorphism so that a variable of a superclass type can hold a reference to an object whose class is any of its subclasses. If a future change simply involves adding a new subclass, the use of inheritance makes the process much simpler. A disadvantage with inheritance however can be the ripple effect of making a small change to the interface of a superclass which requires changes in many other places.

Composition provides an alternative approach towards code reuse that yields easier-to-change code. Using composition the interface of a superclass can be changed, but because the subclass calls the methods on its instance of the superclass it doesn't affect the subclass.

Through the use of abstract multiple inheritance, interfaces can allow composition to take advantage of the dynamic binding and polymorphism benefits without the drawbacks of inheritance. For example, Apple could implement a Fruit interface.

Inheritance is suitable for permanent 'is-a' relationships becuase it can make code easier to understand, in other circumstances composition is likely the correct choice.

No comments: