Java Zero to All All questionsPractise free
Interview questions › Java Foundations — Zero to Basics › OOP II — Inheritance, Polymorphism, Interfaces

What is the Liskov Substitution Principle, and give a concrete way code violates it.

Level III · MidOOP II — Inheritance, Polymorphism, Interfaces
Short answer

LSP says a subtype must be usable anywhere its supertype is expected without breaking the program's correctness — overrides shouldn't strengthen preconditions or weaken postconditions.

Explanation

The textbook violation is Square extends Rectangle: setting width independently of height breaks invariants callers of Rectangle rely on. Another common one is an override that throws UnsupportedOperationException (e.g., an immutable List's add), which technically satisfies the type but violates the behavioral contract callers expect.

Common mistakes
  • Quoting the rectangle/square example without explaining which client expectation breaks.
  • Treating LSP as a rule about method signatures only rather than behaviour.

Can you say this out loud in two minutes? Drill it in a timed mock interview, with flashcards and runnable code for OOP II — Inheritance, Polymorphism, Interfaces.

Practise free

More on OOP II — Inheritance, Polymorphism, Interfaces