Skip to main content

Coupling

Coupling refers to the degree of dependency between modules or components in a system. It determines how much one module relies on another.

There are two types of coupling:

  1. Tight Coupling (High Coupling)
  2. Loose Coupling (Low Coupling)

Tight Coupling (High Coupling)

When one module is highly dependent on another, changes in one module will affect the other.

class Engine {
void start() {
System.out.println("Engine started...");
}
}

class Car {
private Engine engine;

public Car() {
this.engine = new Engine(); // Direct dependency on Engine
}

void drive() {
engine.start();
System.out.println("Car is moving...");
}
}

public class Main {
public static void main(String[] args) {
Car car = new Car();
car.drive();
}
}

Explanation:

  • Here, Car directly creates an instance of Engine, meaning Car is tightly coupled to Engine.
  • If we want to change the Engine class (e.g., introduce a new type of engine), we must modify the Car class.
  • This reduces flexibility and makes the system hard to maintain.

Loose Coupling (Low Coupling)

When modules interact with minimal dependency, making the system more maintainable and flexible.

class Engine {
void start() {
System.out.println("Engine started...");
}
}

// Using Dependency Injection
class Car {
private Engine engine;

public Car(Engine engine) { // Injecting dependency
this.engine = engine;
}

void drive() {
engine.start();
System.out.println("Car is moving...");
}
}

public class Main {
public static void main(String[] args) {
Engine engine = new Engine();
Car car = new Car(engine); // Injecting the Engine instance
car.drive();
}
}

Explanation

  • Now Car does not create an instance of Engine; instead, it accepts an Engine object via the constructor.
  • This follows Dependency Injection (DI), making Car loosely coupled to Engine.
  • If we change Engine, we don’t need to modify Car.