Explain the Open/Closed Principle with a payment example.
Classes should be open for extension but closed for modification. To add a new payment method, write a new class that implements an interface instead of editing the checkout code.
Explain it simply
A power strip lets you plug in a new gadget without rewiring the house. The strip is closed to change but open to extension. Checkout code should behave the same way: it should accept any payment method without being opened up and edited.
Example
interface PaymentMethod { void pay(int rupees); }
class Upi implements PaymentMethod {
public void pay(int r) { System.out.println("UPI " + r); }
}
class Card implements PaymentMethod {
public void pay(int r) { System.out.println("Card " + r); }
}
class Wallet implements PaymentMethod { // added later
public void pay(int r) { System.out.println("Wallet " + r); }
}
class Checkout {
void complete(PaymentMethod m, int amount) { // never edited again
m.pay(amount);
}
}The bad version has if (type.equals("UPI")) ... else if (type.equals("CARD")) inside Checkout. Each new method edits tested code and can break the old branches.
What to say in the interview
"OCP says add behaviour by adding code, not by editing working code. I put a stable interface in front, such as PaymentMethod, and add new implementations. The caller depends only on the interface, so it never changes."
Common mistakes
- Making everything extensible up front. Add the abstraction when the second or third variant appears.