Dependency injection is a way in which we decouple conventional relationships between objects.
“ Dependency injection is a technique whereby one object supplies the dependencies of another object.”
Suppose we are working on a vehicle application and we have two different classes: Car and Bike.
And in the application class, we are trying to instantiate their respective methods to specify what are we driving exactly, a car or a bike?
Now, suppose we don’t want to tide our application class to these specific classes and their methods and want to use the power of Polymorphism to solve this. We will create a parent class/interface named ‘Vehicle’ and have both the classes Bike and Car inherit from it. This will also showcase how we can achieve ‘Dynamic method Dispatch’ or ‘Run Time Polymorphism’ in Java. Check snippets below:
But we are still not getting any benefits out of this approach since in our application class, we are specifically mentioning that the object we are referring is either a car or a bike. So, how to remove free the driving functionality from its dependency on different vehicle objects and just make it rely on parent class, no matter what kind of vehicles try to access it.
Dependency Injection comes to play. We will create a Driving class, which will be driving different vehicles.
And then, we can simply use ‘Driving class’ to set the vehicle we want to drive.