Skip to main content

Command Palette

Search for a command to run...

Open/Closed Principle (OCP) in Java

Updated
3 min readView as Markdown
Open/Closed Principle (OCP) in Java

What is Open/Closed Principle?

The Open/Closed Principle (OCP) is one of the SOLID design principles.

👉 It states:

Software entities (classes, modules, functions) should be open for extension but closed for modification.


💡 Simple Meaning

  • You can add new functionality

  • You should NOT change existing code


Problem Without OCP

Imagine a simple discount calculator:

class DiscountCalculator {

    public double calculateDiscount(String customerType, double amount) {
        if (customerType.equals("REGULAR")) {
            return amount * 0.1;
        } else if (customerType.equals("PREMIUM")) {
            return amount * 0.2;
        }
        return 0;
    }
}

🚨 Issue:

  • Every time a new customer type is added:

    • You must modify this class
  • Violates OCP

  • Leads to:

    • Bug risks

    • Hard maintenance

    • Tight coupling


Applying Open/Closed Principle

We solve this using abstraction (interfaces).


Step 1: Create an Interface

interface Discount {
    double applyDiscount(double amount);
}

Step 2: Create Concrete Classes

class RegularCustomer implements Discount {
    public double applyDiscount(double amount) {
        return amount * 0.1;
    }
}

class PremiumCustomer implements Discount {
    public double applyDiscount(double amount) {
        return amount * 0.2;
    }
}

Step 3: Use It in Main Logic

class DiscountCalculator {

    public double calculateDiscount(Discount discount, double amount) {
        return discount.applyDiscount(amount);
    }
}

Step 4: Usage

public class Main {
    public static void main(String[] args) {

        DiscountCalculator calculator = new DiscountCalculator();

        Discount regular = new RegularCustomer();
        Discount premium = new PremiumCustomer();

        System.out.println(calculator.calculateDiscount(regular, 1000));
        System.out.println(calculator.calculateDiscount(premium, 1000));
    }
}

Now Adding New Feature (NO MODIFICATION!)

Add a new customer type:

class VIPCustomer implements Discount {
    public double applyDiscount(double amount) {
        return amount * 0.3;
    }
}

No change in existing classes ✅

Just extend behavior ✅


Key Benefits of OCP

  • Reduces risk of breaking existing code

  • Makes system scalable

  • Improves maintainability

  • Encourages clean architecture


Before vs After

Without OCP With OCP
Uses if-else logic Uses polymorphism
Hard to extend Easy to extend
Frequent code changes No modification needed
Tight coupling Loose coupling

Real-World Analogy

Think of a mobile charger port:

  • You don’t change the phone’s internal wiring every time

  • You just plug in a new compatible cable

That’s Open for extension, Closed for modification


Conclusion

The Open/Closed Principle helps you build future-proof applications.

💬 “Write code today that won’t need rewriting tomorrow.”


Design Principles for Java Developers

Part 7 of 10

This series explains core Java design principles and SOLID principles with simple examples, real-world use cases, and interview-focused explanations to help developers write clean, maintainable, and scalable code.

Up next

Liskov Substitution Principle (LSP) in Java

Introduction When designing software using inheritance, a common mistake developers make is creating subclasses that change expected behavior. This leads to: Unexpected bugsBroken polymorphismDifficul

More from this blog