What is Dependency Injection in Java: Simple Explanation and Example
interfaces or constructors.How It Works
Imagine you have a coffee machine that needs coffee beans to make coffee. Instead of the machine going out to buy beans itself, someone else provides the beans to it. This is like dependency injection: the machine (object) gets what it needs (dependency) from outside.
In Java, this means a class does not create its own helper objects but gets them passed in. This makes the class simpler and more flexible because you can change the helpers without changing the class. It also makes testing easier because you can give the class fake helpers to test different scenarios.
Example
This example shows a Car class that needs an Engine. Instead of creating the engine inside, the engine is given to the car through the constructor.
interface Engine { void start(); } class DieselEngine implements Engine { public void start() { System.out.println("Diesel engine started"); } } class Car { private Engine engine; // Engine is injected via constructor public Car(Engine engine) { this.engine = engine; } public void startCar() { engine.start(); System.out.println("Car is running"); } } public class Main { public static void main(String[] args) { Engine diesel = new DieselEngine(); Car car = new Car(diesel); // Inject dependency here car.startCar(); } }
When to Use
Use dependency injection when you want to make your code easier to change and test. It is helpful in large projects where many parts depend on each other. For example, in web applications, you can inject different database connections or services without changing the main code.
It also helps when you want to replace parts of your program with new versions or mock objects during testing. Dependency injection frameworks like Spring make this process automatic and clean.
Key Points
- Dependency injection means giving objects their dependencies from outside.
- It improves code flexibility and testability.
- Common ways to inject dependencies are through constructors, setters, or interfaces.
- Frameworks like Spring automate dependency injection in Java.