Skip to the guide

Liskov substitution: subclasses that keep their promises

IntermediateConcept6 pages

The Liskov substitution principle says that an object of a subclass must work anywhere its parent class is expected, without the calling code noticing the difference. Interviewers want to hear the rule behind it, what a subclass may and may not change, and how you would check it with a test.

A hire car "or similar"

You book a mid-size car for a holiday, and the booking says "or similar". The desk may hand you any car from that group, and your booking still holds. "Similar" has rules, even though nobody writes them on the form. The car must take your normal driving licence, so it can't ask more of you than the booking did. It must carry the four people and the luggage the booking promised, so it can't give you less. And every car leaves with a full tank, whatever the model.

In code, the booking is a parent class, here Print, a photo print measured in whole inches, together with the promises its methods make. Each car the desk may hand you is a subclass, here SquarePrint. The licence is a precondition, which is what a method asks of its caller, such as a side from 1 to 100 inches. The people and the luggage are a postcondition, which is what a method promises when it returns, such as a resized print of exactly the size asked for. The full tank is an invariant, which is what stays true of the object all the time, such as its area being its width times its height.