Skip to main content

How do you implement OCP through inheritance?

OCP through inheritance is implemented so that the base class stays unchanged, and new behavior is added as subclasses that override the needed methods. Extension thus happens through new classes rather than changes to old ones.

In detail:

1. The base class defines a common interface

It defines the methods that child classes must implement. This class remains "closed for modification": its code does not change when new behavior variants appear.

2. New behavior types are created through new descendants

When new functionality is needed, a new subclass is created that implements or overrides the needed methods. This provides "openness for extension": the system's behavior grows without changing existing files.

3. Client code works through the base type

No matter how many subclasses exist, external code uses only the base interface. This means adding new implementations does not require changes to the logic that calls these objects.

Example:

python
class PaymentMethod: def pay(self, amount): raise NotImplementedError

Child classes:

python
class CardPayment(PaymentMethod): def pay(self, amount): print("Card payment:", amount) class PayPalPayment(PaymentMethod): def pay(self, amount): print("PayPal payment:", amount)

Extension:

python
class CryptoPayment(PaymentMethod): def pay(self, amount): print("Crypto payment:", amount)

Why this satisfies OCP

  1. The base class was never changed It remained closed for modification.
  2. New behavior was added through a new descendant CryptoPayment is a new variant that does not require rewriting old classes.
  3. Client code uses a single interface For example:
python
def checkout(payment: PaymentMethod, amount): payment.pay(amount)

This code needs no changes when new payment methods are added.

Summary: Inheritance implements OCP when the base class defines a contract, and new behavior is added solely by creating new subclasses, without changing the existing ones.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.