Liskov Substitution Principle: Why Subclasses Must Honor Parent Class Contracts
The Liskov Substitution Principle (LSP) is a core object-oriented design rule stating that subclass objects must be interchangeable with their parent class without breaking application behavior. A classic violation is modeling a Square as a subclass of Rectangle — while geometrically valid, overriding setWidth and setHeight to enforce equal sides silently corrupts calculations expected by parent-class consumers. The recommended fix is to avoid forcing such relationships through direct inheritance and instead use a shared interface, like a Shape interface with a getArea method, so each class independently fulfills the contract. Following LSP improves code reliability, predictability, and enables safe polymorphic behavior across a codebase.
This is an AI-generated summary. ShortSingh links to the original source for the complete article.
Discussion (0)
Log in to join the discussion and vote.
Log in