Last Updated: 25.02.2026
Open-closed Principle (OCP) states:
Objects or entities should be open for extension but closed for modification.
👉 Open for Extension
👉 Closed for Modification
This means that:
✅ You should be able to add new behavior
❌ Without changing existing working code
In real companies:
- Features keep changing
- New business rules come
- Payment providers change
- New user roles are added
If every new feature forces you to edit old code → you break existing logic.
That’s dangerous in production systems.
Let’s say we are building a payment system.
public class PaymentService {
public void processPayment(String type) {
if (type.equals("CREDIT_CARD")) {
System.out.println("Processing credit card payment");
}
else if (type.equals("UPI")) {
System.out.println("Processing UPI payment");
}
}
}❌ Problem - Now business says: Add PayPal, Add Crypto, Add Net Banking
Every time you must:
- Modify this class
- Add another
else if - Retest everything
🔥 This violates OCP because:
- Class is NOT closed for modification
- You must change it to add new behavior
Instead of modifying existing class, we extend behavior.
👉 Step 1: Create an Interface
public interface PaymentMethod {
void pay();
}👉 Step 2: Create Implementations
public class CreditCardPayment implements PaymentMethod {
public void pay() {
System.out.println("Processing credit card payment");
}
}public class UpiPayment implements PaymentMethod {
public void pay() {
System.out.println("Processing UPI payment");
}
}👉 Step 3: Modify PaymentService (Only Once)
public class PaymentService {
public void processPayment(PaymentMethod paymentMethod) {
paymentMethod.pay();
}
}👉 Step 4: Usage
PaymentService service = new PaymentService();
service.processPayment(new CreditCardPayment());
service.processPayment(new UpiPayment());👉 Now What Happens If the requirement comes to add new payment method?
We can add new class without modifying existing class by extending the PaymentMethod interface.
❇️ Let's say, we want to add PayPal Payment method.
public class PaypalPayment implements PaymentMethod {
public void pay() {
System.out.println("Processing PayPal payment");
}
}👉 We DO NOT modify PaymentService, Rather we just extend system.
🔥 That is OCP.
🗣️ Interviewer may ask: “How does OCP relate to Strategy Pattern?”
🧑💻 Answer: OCP is a principle and Strategy is a design pattern that helps implement OCP
If you see:
if(type == X)
else if(type == Y)
else if(type == Z)| Without OCP | With OCP |
|---|---|
| if-else chain | Polymorphism |
| Hard to scale | Easy to extend |
| Risky changes | Stable core |
| Tight coupling | Loose coupling |
Open Closed Principle means:
✔ Open for extension
✔ Closed for modification
✔ Use interfaces
✔ Use polymorphism
✔ Avoid modifying stable code
✔ Extend behavior instead
