intermediateLiskov Substitution Principle

Why does the classic 'Square extends Rectangle' design violate the Liskov Substitution Principle?

If Rectangle exposes independent setWidth() and setHeight() methods, a caller can reasonably assume setting one doesn't affect the other. Square, to keep its sides equal, must override both setters so that changing width also changes height and vice versa — which silently breaks that assumption for any code written against Rectangle. A test that creates a Rectangle, sets width to 5 and height to 10, and asserts the area is 50 will fail if it's secretly handed a Square instance, even though Square passes every structural check a Rectangle requires. The deeper lesson is that a real-world "is-a" relationship, which is mathematically true here, doesn't automatically translate into safe behavioral substitutability in code, since substitutability depends on preserved behavior, not just a valid conceptual category.

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

Next Step

Continue to What does Abstract Factory guarantee that using several independent Factory objects cannot?← Back to all Low-Level Design & Design Patterns questions