Wednesday, May 1, 2019

Inheritance vs Composition

Inheritance is an "is-a" relationship. Composition is a "has-a".

Example: Car is a Automobile and Car has a Engine.

class Engine {} // The Engine class.

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

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

**************************************************************************

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 class X{ 
   public void do(){ 
   }
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. 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 :
composition is easily achieved at runtime while inheritance provides its features at compile time.

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

Summary:-
Composition - has-a relationship between objects.
Inheritance - is-a relationship between classes.

Composition - Composing object holds a reference to composing classes and hence relationship is loosely bound.
Inheritance - Derived object carries the base class definition in itself and hence its tightly bound.

Composition - Used in Dependency Injection
Inheritance - Used in Runtime Polymorphism

Composition - Single class objects can be composed within multiple classes.
Inheritance - Single class can only inherit 1 Class.

Composition - Its the relationship between objects.
Inheritance - Its the relationship between classes.

No comments:

Post a Comment

Web Development

Design Phase:- Below all these represent different stages of the UX/UI design flow:- Wireframes represent a very basic & visual repr...