Friday, July 17, 2015

Prefer Composition over Inheritance

In Inheritance, a new class, which wants to reuse code, inherit an existing class, known as super class. This new class is then known as sub class. On composition, a class, which desire to use functionality of an existing class, doesn't inherit, instead it holds a reference of that class in a member variable, that’s why the name composition.

Inheritance - IS-A relation
Composition -Has-A relation

Java dosent support multiple inheritance. So, to use multiple functionality from different classes and having them as members variables. This is in a way composition. Implement classes using interfaces and use these class instances in the needed class is the best way to go.

Composition offers best test-ability of a class than inheritance.

Best examples to prove favors for composition over inheritance is Strategy design pattern and Decorator design pattern. In all these examples we do not extend to add functionality instead use member variables to do that job.

When inheritance is used the biggest drawback is that if there is any change in the super class there is high chance of the subclass to be broken in its functionality.

By using composition over inheritance one important advantage is that at any time a better implementation can be added on needed bases since a new version be added and passes the reference of this new version to the base class and it would take this new implementation.

More detailed explanation on this topic is given at link: http://javarevisited.blogspot.com/2013/06/why-favor-composition-over-inheritance-java-oops-design.html