SOLID: L — Liskov Substitution Principle

Objects of a subclass must work anywhere the parent class is expected, without breaking the program.

Why it matters

Polymorphism only works if every subtype really behaves like its parent. One misbehaving subclass forces callers to add special cases, and bugs appear far away from their cause.

The idea

A subclass must keep its parent's promises. It can't demand more (stricter inputs) or deliver less (weaker results), and it shouldn't throw surprises. If calling code has to check 'is this the special subclass?', the principle is broken.

A substitute teacher: lessons should run normally. If the substitute refuses to teach maths, the school timetable breaks.

A human substitute can explain what's different. Code can't, so the contract — what methods accept and guarantee — must be clear.

How it works

  1. Write down what callers rely on: 'after set_width(5), the width is 5 and the height hasn't changed'.
  2. Check that every subclass keeps that promise. Square breaks it: setting the width also changes the height.
  3. If a subclass can't keep a promise, it isn't a true subtype for that behaviour.
  4. Fix it with a different hierarchy: Rectangle and Square both implement a Shape interface with area(), and there are no setters that conflict.

Example

The classic case: Square inheriting from Rectangle. Code that sets width = 5 and height = 4 expects an area of 20, but a Square keeps its sides equal and gives 16. So Square shouldn't extend a changeable Rectangle.

Key points

Common mistakes

Not true: Overriding a method to throw 'not supported': allowed, and code written for the parent still works.
In fact: Code written for the parent calls that method and now crashes. A subclass must keep the parent's promises; if it can't, the abstraction is wrong.

In the interview

Liskov means a subclass must work anywhere its parent does. The classic counter-example is Square extending Rectangle: setting width and height separately breaks for a square, so they shouldn't share that inheritance.

Part of Unit 5: Low-level design: OOP and SOLID in the free System Design course.