Fundamentals · Hard · Free
Explain the Liskov Substitution Principle with a violation example.
FresherFundamentalsOOP & Language Fundamentals
Liskov Substitution Principle
Subtypes must be substitutable for their base type without breaking callers. If code expects a Bird.fly(), a Penguin subclass that throws breaks LSP.
java
class Rectangle { void setWidth(int w); void setHeight(int h); }
// Square overriding setters breaks rectangle expectations — LSP violationFix: smaller interfaces (
FlyingBird) instead of forcing square into rectangle hierarchy.