Tuesday, April 03, 2012

Favor Composition to Inheritance

As we all know Java is an Object-Oriented Programming Language. OOP was developed in first place to increase code reuse and maintainability.

The Myth

Programmers introduced to OOP Language(s) have a mindset that code reuse can be achieved only by Inheritance (extends) in Java. But are not aware of the alternatives even if they came across them.

For Example:

List<Car> carRef = new ArrayList<Car>();  //Generic List of Car References

Q.  Why Inheritance is considered bad?

A.  Experienced Programmers are aware of the fact and even the Design Patterns states the same using Inheritance across boundaries are considered bad as author of that library may change the internal implementation details which might break our abstraction that depends on it blowing up the whole stack.

Better Alternative - Prefer Composition to Inheritance

I will soon add more on this. Please do post your comments if your thinking differs from me. I will try to incorporate you questions/suggestion here so everyone has a better idea on this concept.

Hope this Helps! Please write your comments it will help me improve.


  1. Inheritance stands for the "is a" concept, not for code reuse, that's the real problem.

    1. Inheritance is a way to achieve code reuse but yes may not be the best available as alternatives are available... :)

  2. It may be worthwile to compare subtype polymorphism to parametric polymorphism the way you started to do it:

    While subtyping is useful only in quite narrow situations where a car IS INDEED a vehicle, which IS INDEED an object, parametric polymorphism embraces the "composition pattern" as you call it, where lists CONTAIN cars, but they ARE NOT "car lists".

    So I'd be curious how your article will proceed...

    1. Hi Lukas,

      Parametric Polymorphism -> applies to Generics in Java as far as I know. So there is no intention here for me to compare the two. :)

      Thanks for the concern. I really wanted to write this article to show the working of the two concepts and places where one can choose between the two without any hesitation. I really failed so far but I'm working on it and will try to improve this article when I get more time to think and write. I'll appreciate all the inputs that comes my way and will try to incorporate all into one big good informative post. :)