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:
- Tight Coupling (High Coupling)
- 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,
Cardirectly creates an instance ofEngine, meaningCaris tightly coupled toEngine. - If we want to change the
Engineclass (e.g., introduce a new type of engine), we must modify theCarclass. - 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
Cardoes not create an instance ofEngine; instead, it accepts anEngineobject via the constructor. - This follows Dependency Injection (DI), making
Carloosely coupled toEngine. - If we change
Engine, we don’t need to modifyCar.