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?
Composition offers better test-ability of a class than Inheritance. If one class consists of another class, you can easily construct a Mock Object representing a composed class for the sake of testing. This privilege is not given by inheritance.
The disadvantage of object composition is that the behavior of the system may be harder to understand just by looking at the source code. A system using object composition may be very dynamic in nature so it may require running the system to get a deeper understanding of how the different objects cooperate.
The composition approach provides stronger encapsulation than inheritance, because a change to a back-end class does not necessarily break any code that relies on the front-end class. The main advantages of composition is, with carefully designed interfaces we can change references of back end classes at runtime.
Inheritance and composition are two programming techniques developers use to establish relationships between classes and objects. Whereas inheritance derives one class from another, composition defines a class as the sum of its parts.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With