Difference between Inheritance and Composition Difference between Inheritance and Composition java java

Difference between Inheritance and Composition


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 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.}


How inheritance can be dangerous ?

Lets take an example

public class X{       public void do(){       }    }    Public Class Y extends X{   public void work(){           do();       }}

1) As clear in above code , Class Y has very strong coupling with class X. If anything changes in superclass X , Y may break dramatically. Suppose In future class X implements a method work with below signature

public int work(){}

Change is done in class X but it will make class Y uncompilable. SO this kind of dependency can go up to any level and it can be very dangerous. Every time superclass might not have full visibility to code inside all its subclasses and subclass may be keep noticing what is happening in superclass all the time. So we need to avoid this strong and unnecessary coupling.

How does composition solves this issue?

Lets see by revising the same example

public class X{    public void do(){    }}Public Class Y{    X x = new X();        public void work(){            x.do();    }}

Here we are creating reference of X class in Y class and invoking method of X class by creating an instance of X class.Now all that strong coupling is gone. Superclass and subclass are highly independent of each other now. Classes can freely make changes which were dangerous in inheritance situation.

2) Second very good advantage of composition in that It provides method calling flexibility, for example :

class X implements R{}class Y implements R{}public class Test{        R r;    }

In Test class using r reference I can invoke methods of X class as well as Y class. This flexibility was never there in inheritance

3) Another great advantage : Unit testing

public class X {    public void do(){    }}Public Class Y {    X x = new X();        public void work(){            x.do();        }    }

In above example, if state of x instance is not known, it can easily be mocked up by using some test data and all methods can be easily tested. This was not possible at all in inheritance as you were heavily dependent on superclass to get the state of instance and execute any method.

4) Another good reason why we should avoid inheritance is that Java does not support multiple inheritance.

Lets take an example to understand this :

Public class Transaction {    Banking b;    public static void main(String a[])        {            b = new Deposit();            if(b.deposit()){                b = new Credit();            c.credit();            }    }}

Good to know :

  1. composition is easily achieved at runtime while inheritance provides its features at compile time

  2. composition is also know as HAS-A relation and inheritance is also known as IS-A relation

So make it a habit of always preferring composition over inheritance for various above reasons.