Dependency Injection in simple Term

Piyuri Sahu
1 min readFeb 16, 2021

Dependency injection also called dependency inversion. The idea is to decouple conventional relationship between object. Basically remove dependency between them by inject dependency by other entity outside the class.

class Draw {
private Shape shape;

public void drawShap() {
shape = new Circle();
shape.draw();
}
}

In this example Draw class is tightly coupled with Shape object. Draw class knows what it is drawing and It can only draw triangle.

what about this code?

class Draw {

public void setShape(Shape shape) {
this.shape = shape;
}

private Shape shape;

public void drawShap() {
shape.draw();
}
}

Here Draw does not know anything about shape, does not know what it is drawing because it does not own the actual shape it is drawing.

You can pass any type of shape(circle, trianlge, square) to Draw class, it will draw the shape. Here, we have inverted the dependency. So basically enternal entity will provide Shape object.

public class DependencyInjectionTest {
public static void main(String[] args) {
//
Draw drawCircle = new Draw();
drawCircle.setShape(new Circle());
drawCircle.drawShap();

drawCircle.setShape(new Triangle());
drawCircle.drawShap();

drawCircle.setShape(new Sqare());
drawCircle.drawShap();
}
}

--

--

Piyuri Sahu

Application-developer at Technogise Software Solution