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?
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.Propertiesclass 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.