Dependency Injection

Dependency Injection is a way of resolving dependencies of any Class by asking for them instead creating themselves.

Let’s talk with example. Say you have one class Car which has one dependency on other class like Engine. So we can declare our Car class like below.

public class Car {
   private Engine engine = new Engine();
}

So whats wrong with it?

  • First, its not really suggestive to use new keyword in Java at this place.
  • Second, This is an example of HAS-A relationship (between Car and Engine) of Composite type. Which is wrong. Read my Composition vs Aggregation blog to understand better.
  • Third, When Car object is set to null, there is no way you can recover Engine object.

If you can think practically the relationship between Car and Engine. You can easily pull out the Engine from any Car and put it in any other Car. In technical terms, Engine can exist WITHOUT a Car. So how to design such class? It goes like below…

public class Car { 
   private Engine engine;

   public void setEngine(Engine engine){ 
    this.engine = engine;
   }
   public Engine getEngine(){ 
      return engine;
   }
}

By writing our Car class this way, we can easily say that Car has Engine which can be set by calling setter method of Car class i.e.¬†setEngine(…). The above code is an example of HAS-A relationship in Aggregate way.

Let me explain the above statement with code.

public class CarApplication {
   public static void main(String[] args) {
       Engine engine = new Engine();
       Car car = new Car();
       car.setEngine(engine);    
   }
}

So in the above code we are first creating one Engine and then setting that Engine in Car.

In this way both Car and Engine objects are free and can exist without each other. Specially Engine object can exist without Car object’s existenc.

Hope this clear your doubts!!


One thought on “Dependency Injection

Comments are closed.