Why is OCP closely tied to interfaces?
OCP is closely tied to interfaces because interfaces are exactly what allow extending behavior without changing existing code, which is the essence of the open/closed principle.
In detail:
1. An interface defines a contract that does not need to change
An interface defines a set of methods but not their implementation. This contract stays stable - it is "closed for modification". As long as the interface does not change, all the code that depends on it stays unchanged.
2. New interface implementations are the path to extension
When a new need appears, a new implementation of the interface is created. This is "openness for extension": the system gets new behavior without changing existing classes.
3. Client code works with abstractions, not concrete classes
Code that uses an interface does not know, and should not need to know, which specific implementation is plugged in. This allows new behavior variants to be added without touching the calling code.
4. Interfaces remove the need to modify central logic
Without interfaces, extension usually requires:
- adding new
if/elsebranches, - extending a
switch, - adding new condition branches. All of this is a violation of OCP. An interface eliminates this construct: the choice of behavior is moved onto the object rather than a conditional statement.
5. Interfaces enable polymorphism
Polymorphism is the key mechanism for implementing OCP. Thanks to an interface, different implementations can be substituted without the rest of the system noticing.
6. An interface makes the system flexible to changing requirements
Requirements always change, but an interface fixes the boundary: a stable contract → changeable implementations. This is exactly what OCP requires.
Summary: OCP is tied to interfaces because interfaces fix a stable contract, and extension happens through new implementations of that contract, without changing existing code. This makes the system resilient to change and safe to evolve.
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.