CSE Roadmap

Core tier · about 3 hours · 6 parts

Part 5 of 6 · 2 min read

A checklist

What a subclass may and may not do.

A checklist for subclasses

The following rules follow from Liskov's definition. They are common practice and are not quoted from one chapter.

  • A subclass may accept the same inputs as the parent, or more. It must not demand more. If the parent takes any number of hours, the subclass must not refuse hours above 4.
  • A subclass must give the same guarantees as the parent, or stronger ones. If the parent promises a non-negative price, the subclass must not return minus 5.
  • A subclass must not throw new kinds of exceptions that callers of the parent do not expect.
  • A subclass must keep the parent's invariants. An invariant is a fact that is always true of an object, for example "end time is after start time".
  • Equals comparisons must stay consistent. EJ Item 10 shows that a subclass which adds a field and includes it in equals breaks symmetry or transitivity, and that there is no way to extend a class with a value component and keep the contract. EJ's remedy is composition: hold the base object in a field instead of extending it.

A short habit helps. Before writing extends, finish the sentence "everywhere the parent works, this subclass works because...". If the sentence is hard, write an interface and composition instead.

Interview angle

Answer in your head first, then open it.

State LSP.

Code that uses a parent type must work unchanged with any subclass, without type checks.

Give a violation.

A square extending a mutable rectangle, where setting width and then height gives the wrong area.

How do you avoid it?

Inherit only when behaviour matches. Otherwise use an interface with the common promises, or composition.

Words you will meet

Word Meaning
Subtype A type that can stand in for another
Substitution Using a subtype where the parent type is expected
Invariant A fact that must always hold for an object
Contract The promises a method makes about inputs and results
Type check instanceof or similar code that asks which subclass it is