Thursday, August 27, 2015

Composition vs Inheritance in OOPS

Composition - Having a Has-A relationship and simply uses instance variable that are references of other objects.
Inheritance - Having IS-A relationship and simply access state and behaviour of other object by inheriting it. 

Ex. Hyundai is-A Car (Inheritance) Has-A Engine (Composition)


 Properties
Inheritance
Composition
Flexibility
When you use Inheritance, you have to define which class you are extending in code; it cannot be changed at runtime. 
Composition you just define a Type which you want to use, which can hold its different implementation.
Code Reuse
Inheritance you can only extend one class, which means you code can only reuse just one class, not more than one. 
If you want to leverage functionalities from multiple classes, you must use Composition.
Unit Testing
When you design your class using Inheritance, you must need parent class in order to test child class. There is no way you can provide mock implementation of parent class.
When you design classes using Composition they are easier to test because you can supply mock implementation of the classes you are using
Final Classes
You cannot inherit final classes, hence you cannot reuse code of final class
Composition allows code reuse even from final classes
Encapsulation
Inheritance breaks encapsulation because in case of Inheritance, sub class is dependent upon super class behaviour. If parent classes changes its behaviour than child class is also get affected. If classes are not properly documented and child class has not used the super class in a way it should be used, any change in super class can break functionality in sub class.
Composition doesn't break encapsulation.If main class changes its behaviour then calling class doesn't get affected. 

  • Don't use inheritance just to get code reuse If all you really want is to reuse code and there is no is-a relationship in sight, use composition.
  • Don't use inheritance just to get at polymorphism If all you really want is polymorphism, but there is no natural is-a relationship, use composition with interfaces.

No comments:

Post a Comment