The Artima Developer Community
Sponsored Link

Interface Design by Bill Venners
Understand the difference between inheritance and composition

Advertisement

Interface Design | Contents | Previous | Next

Stack extends Vector is a great example of where is-a wasn't really satisfied, and composition would have been much more flexible. Also, the Vector methods didn't really belong in Stack. When the retrofitted Vector to implement List, a whole bunch of other methods got added to the Stack interface.

A big part of the adapter pattern's significance is that it shows that objects involved in a composition relationship have interfaces that are independent of each other.

Ripple effect from changing a back-end class stops (or can stop) at the front-end class


Composition vs. Inheritance

Inheritance Yields (Slightly) Better Performance: Composition Yields Better Flexibility: But:

Describe adding method to superclass that has same name but different semantics as subclass. Also the problem of just inheriting an added method signature that you don't want in the subclass.

Class extension (full-blown inheritance -- interface and implementation) is like strapping on a backpack in which your instances carry around not only their own instance variables and everything they refer to in a graph of objects, but also those of all their superclasses. If you don't own the superclass, owner can change superclss by adding lots of heavy instance data that gets added to your backpack and you don't have a choice but carry it around everywhere. The owner can also add a method to the superclass interface that you don't like in your subclass, but suddently its a part of your interface whether you like it there or not (or, what's the ultimate problem has, the same signature but incompatible semantics as an existing method in your subclass). If the superclass owner adds lots of heavy instance data to the superclass, that owner basically has added all that weight to your subclass instance's backpack. Your subclass instances have no choice but carry that around everywhere they go. (In a composition relationship you could change the back-end object, delay initilization until needed, share same backend amont multiple front-ends, etc...)

Could show the decorator example from chapter 4 in UML form and mention the intent thing?


Sponsored Links



Google
  Web Artima.com   
Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use