OOPs4Humans

Dependency Injection

Giving objects what they need instead of letting them make it.

Dependency Injection

Analogy: concept

Dependency Injection (DI) is like Changing Batteries:

You don't solder a battery into a remote control. You provide a slot so you can swap batteries (AA, AAA, Rechargeable) easily.

The remote doesn't care which battery it is, as long as it fits.

The Injector

Inject different engines into the car. The car works with any engine because it depends on the interface, not the specific implementation.

Dependency Injection (The Injector)

1. Inject Dependency

No Engine

Key Concepts

  1. Dependency: An object that another object needs to function (e.g., Car needs an Engine).
  2. Injection: Passing the dependency from the outside (via constructor or setter) rather than creating it inside.
  3. Inversion of Control (IoC): Giving control of dependency creation to a framework or caller.

The Code

Without DI (Bad):

Java Example
Switch language in Navbar
class Car {
    private GasEngine engine;
    
    Car() {
        engine = new GasEngine(); // Hardcoded! Can't use ElectricEngine.
    }
}

With DI (Good):

Java Example
Switch language in Navbar
class Car {
    private Engine engine;
    
    // Inject via Constructor
    Car(Engine e) {
        this.engine = e; // Flexible! Can be Gas, Electric, or Hybrid.
    }
}