🔗 What Is Coupling?
Coupling means how strongly one class is connected to another class in your program.
🔴 Tightly Coupled
- One class is directly dependent on another.
- If you change one class, the other may break.
- Think of it like two people walking with their shoelaces tied together—one trip and both fall.
👀 Simple Example:
class Engine {
void start() {
System.out.println("Engine started");
}
}
class Car {
Engine engine = new Engine(); // tightly connected
void drive() {
engine.start();
}
}
In this example, the Car
class knows exactly which Engine
it needs. You can’t easily swap the engine.
🟢 Loosely Coupled
- One class depends on what the other class can do, not how it does it.
- Classes are connected using interfaces, not specific classes.
- It’s like using a charger that works with any phone—as long as it supports the same plug.
👀 Simple Example:
interface Engine {
void start();
}
class PetrolEngine implements Engine {
public void start() {
System.out.println("Petrol engine started");
}
}
class Car {
Engine engine;
Car(Engine engine) {
this.engine = engine;
}
void drive() {
engine.start();
}
}
Now you can use any kind of engine—just pass it to the Car
when you create it.
🧠 Why This Matters (Short & Sweet)
Type | Easy to Change? | Easy to Test? | Reusable? |
---|---|---|---|
Tightly Coupled | ❌ No | ❌ No | ❌ No |
Loosely Coupled | ✅ Yes | ✅ Yes | ✅ Yes |