Return to site

What is the Open/Closed Principle in Java?

· java,interview,video

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

It states:

✅ Open for extension – You should be able to add new functionality

❌ Closed for modification – You shouldn’t have to change existing code to do it

🛠️ Why it matters?

- Prevents breaking existing code when adding new features

- Encourages writing flexible, maintainable, and scalable code

- Reduces bugs when making changes

🔍 Example

- Instead of modifying a class directly to add new behavior, you:

Use interfaces and abstract classes

- Apply polymorphism to extend functionality without touching the original code

💡 OCP = Evolve your code without breaking it.