2

Possible Duplicate:
Prefer composition over inheritance?

I wonder, why (or in which cases) should one consider inheritance instead of composition when there are so much cons of it:

  • if we implement/override a method in a subclass which calls the method of the superclass, there's no guarantee that another version of our superclass (maybe some library) won't break our code
  • if there will appear a new method in the superclass with the same signature that the sublclass method has, but with different return type, our class won't compile.

Therefore, I can't imagine, how on Earth we can rely on it. The superclass author may want to improve the performance and our client code may break down.

So my questions are:

  • How are these problems solved (e.g. in standard Java libraries)?
  • When to use inheritance and composition?
Community
  • 1
  • 1
iozee
  • 1,339
  • 1
  • 12
  • 24
  • 2
    http://stackoverflow.com/questions/49002/prefer-composition-over-inheritance?rq=1 http://stackoverflow.com/questions/216523/object-oriented-best-practices-inheritance-v-composition-v-interfaces?rq=1 http://stackoverflow.com/questions/1598722/should-i-use-inheritance-or-composition?rq=1 – adarshr Jun 14 '12 at 11:11
  • Ok, but I still can't find the answer to my 1st question. – iozee Jun 14 '12 at 11:15
  • 2
    The problems you are describing have nothing to do with the composition vs inheritance issue. For example, if a method signature changes, *any* code that uses will break it, including any delegator methods in any composite classes. – thkala Jun 14 '12 at 11:19
  • There is a huge number of greate posts about inheritance and composition. But my pragmatic approach: use what will give you clean compact code, easy to maintain and support. And in different cases this can be inheritance and in other cases - composition. – alexey28 Jun 14 '12 at 11:25

1 Answers1

6

Your first objection also applies to composition: if the implementation of a method that you call changes, there's no guarantee that your code won't break.

The second objection is actually a good thing, since you'll immediately notice there is a problem with the new version of the API.

The problem doesn't have much to do with inheritance/composition. If the public contract of a class changes from version to version, you'll have to make changes in your code to accomodate these changes. The problem is solved by avoiding changes that would be backward-incompatible. Providing a new API can be the solution (See io, followed by nio, followed by nio2, for example). Otherwise, release notes and migration documentation are there to help transitioning from one version of an API to another.

Inheritance is used when there is a is-a relationship between your class and the other class. Composition is used when there is a has-a relationship between your class and the other class.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255