Favor composition over inheritance [duplicate]

Favor composition over inheritance

is very popular phrase. I read several articles and at the end each article says

use inheritance when there is pure IS-A relationship between classes.

An example from this article:

Here between Apple and Fruit there is clear IS-A relationship i.e Apple IS-A Fruit, yet the author has also shown it as Apple HAS-A Fruit (composition) to show the pitfall when implemented with inheritance.

I became somewhat confused here that what is the meaning of statement

use inheritance when there is pure IS-A relationship between classes.

Does using composition over inheritance mean that always try to apply composition even if there is a pure IS-A relationship and leave inheritance only for those cases where composition does not make sense?


Solution 1:

When you use inheritance to reuse code from the superclass, rather than to override methods and define another polymorphic behavior, it's often an indication that you should use composition instead of inheritance.

The java.util.Properties class is a good example of a bad use of inheritance. Rather than using a Hashtable to store its properties, it extends Hashtable, in order to reuse its methods and to avoid reimplementing some of them using delegation.

Solution 2:

I think this is one of the most discussed point in Object Oriented design. As suggested in the article, composition is always preferred over inheritance. That doesn't mean that you should never use inheritance. You should where it makes more sense (which can debatable).

There are many advantages of using composition, couple of them are :

  • You will have full control of your implementations. i.e., you can expose only the methods you intend to expose.
  • any changes in the super class can be shielded by modifying only in your class. Any clients classes which uses your classes, need not make modifications.
  • Allows you to control when you want to load the super class (lazy loading)