Composition

Using some functionalities of a class but doesn't inherit (i.e. is-a relationship) it, is known as composition (i.e. has-a relationship).

Reasons to Favor Composition Over Inheritance

  • Composition offers a better testability. Imagine a class composed of another class or interface. You can easily create a mock of the composed class for the sake of testing.
  • Composition is more flexible than inheritance. It is easier to change the implemention of the composed class with better and improved version. Just create a new independent implementation (e.g. annonymously) of the composed class and change it at runtime.
  • Both composition and inheritace supports code reuse. However, inheritance breaks encapsulation. Example, if a subclass is depending on its super class behavior for its operation, it becomes fragile. Try to imagine that you change the implementation on the super class. Did you consider the effect of the change on the subclasses that overrides it but partially depends on it. In composition there's no dependencies like this. Thus, you have more robust code.