Dependency Inversion Principle in Java

Dependency Inversion Principle states to “Depend on abstractions and not upon concretions”.

What this principle means is that rather than writing code that refers to concrete classes, you should code for Interfaces and Abstract classes.

For example, if Class B instantiates Class A, then it gets dependent on the Class A.

Class A {
    // ...

Class B {
    A a = new A();

With the above code, Class B now depends on Class A.
However if we refer the interface of A (say IA), then if needed we can later change to a different implementation, may be A2.
Interface IA {

Class A implements IA{

Class A2 implements IA{

Class B{
    //IA a = new A();
    //We can replace A with a different implementation A2
    IA a = new A2(); 

We can use this to unit test code by using fake or mock classes that mock out classes thereby making it easier to unit test a class’s code in isolation.


References :

Image Ref :

© 2017, https:. All rights reserved. On republishing this post, you must provide link to original post

Leave a Reply.. code can be added in <code> </code> tags