What does it mean for a class to be 'open for extension but closed for modification'?
"Open for extension" means new behavior can be added to a system, and "closed for modification" means adding that new behavior should not require editing a class's existing, already-tested source code. In practice this is usually achieved through polymorphism: a stable class depends on an interface or abstract type, and new behavior is introduced by writing a brand-new class that implements that type, rather than by adding a new conditional branch to the stable class itself. A PaymentProcessor that calls paymentMethod.pay(amount) through an interface is closed, because supporting a new payment method means writing one new class and never touching PaymentProcessor's own source. The benefit is risk isolation — code that already works and is already trusted in production is never put back in play just to add something new.
Ready to master this question?
Generate a complete walkthrough — background, the full answer in plain language, a working code example explained line by line, a real-world scenario, common mistakes, and how this same question gets asked in different ways.
Sign in to generate a response