Difference between Inheritance and Composition

Solution 1:

They are absolutely different. Inheritance is an "is-a" relationship. Composition is a "has-a".

You do composition by having an instance of another class C as a field of your class, instead of extending C. A good example where composition would've been a lot better than inheritance is java.util.Stack, which currently extends java.util.Vector. This is now considered a blunder. A stack "is-NOT-a" vector; you should not be allowed to insert and remove elements arbitrarily. It should've been composition instead.

Unfortunately it's too late to rectify this design mistake, since changing the inheritance hierarchy now would break compatibility with existing code. Had Stack used composition instead of inheritance, it can always be modified to use another data structure without violating the API.

I highly recommend Josh Bloch's book Effective Java 2nd Edition

  • Item 16: Favor composition over inheritance
  • Item 17: Design and document for inheritance or else prohibit it

Good object-oriented design is not about liberally extending existing classes. Your first instinct should be to compose instead.


See also:

  • Composition versus Inheritance: A Comparative Look at Two Fundamental Ways to Relate Classes

Solution 2:

Composition means HAS A
Inheritance means IS A

Example: Car has a Engine and Car is a Automobile

In programming this is represented as:

class Engine {} // The Engine class.

class Automobile {} // Automobile class which is parent to Car class.

class Car extends Automobile { // Car is an Automobile, so Car class extends Automobile class.
  private Engine engine; // Car has an Engine so, Car class has an instance of Engine class as its member.
}