Woodstock Blog

a tech blog for general algorithmic interview questions

[Design] Composition Over Inheritance


Composition over inheritance in OOP is a technique by which classes achieve polymorphic behavior and code reuse by containing other classes instead of through inheritance.


It gives the design higher flexibility, giving business-domain classes and more stable business domain in the long term. In other words, HAS-A can be better than an IS-A relationship.

And inheritance breaks encapsulation! This post also points out these (which is hard to understand):

  1. You can’t change the implementation inherited from super classes at runtime (obviously because inheritance is defined at compile time).

  2. Inheritance exposes a subclass to details of its parent’s class implementation, that’s why it’s often said that inheritance breaks encapsulation (in a sense that you really need to focus on interfaces only not implementation, so reusing by sub classing is not always preferred).

  3. The tight coupling provided by inheritance makes the implementation of a subclass very bound up with the implementation of a super class that any change in the parent implementation will force the sub class to change.

  4. Excessive reusing by sub-classing can make the inheritance stack very deep and very confusing too.