How does OCP work with inheritance vs composition?

Answer

OCP can be implemented through both inheritance and composition, but they have different trade-offs. Inheritance-based OCP: a base class provides default behavior, subclasses override to extend — the classic Template Method pattern. The risk is fragile base class problem — changes to the base class can unintentionally break subclasses. Composition-based OCP (preferred): a class delegates behavior to an interface, and new behavior is added by creating new implementations. This follows the Gang of Four advice: "prefer composition over inheritance." Composition-based OCP is more flexible because implementations can be mixed and matched at runtime, while inheritance is fixed at compile time. The Strategy, Decorator, and Chain of Responsibility patterns all use composition to achieve OCP.