CS 4448 - Fall 1998
Object-Oriented Programming and Design
Talk 10.4
by
Derek Reiger
Inheritance versus composition: Which one should you choose?
by
Bill Venners
- Inheritance - a new class is created from and existing class and
inherits the properties of that existing class. It models an is-a relationship.
- Composition - a front-end class holds a reference to a back-end
class in one of its instance variables. It models a has-a relationship.
- The goal of this paper is to influence the reader to choose the
best relationship model for their design, specifically with regard to code
reuse.
- Inheritance may not be the best relationship model if the goal is
code reuse because changes to a superclass interface can break code that
uses the superclass or any of its subclasses.
- Composition might be a better solution because changes might be
limited to referenced classes, but code that uses those classes should
be safe.
- Guidelines to go by:
- Make sure inheritance actually models the is-a relationship.
- If the goal is specifically code reuse, composition offers more
maneagable changes.
Copyright © University of Colorado. All rights reserved.
Revised: November 16, 1998