Part 5 of 7 · 1 min read
Safe substitution
A subtype must keep the promises of its parent.
Polymorphism works only when each object truly can stand in for the type it claims. GoF says that when inheritance is used carefully, all classes derived from an abstract class share its interface, so a subclass adds or overrides operations and does not hide any of the parent's. Then all subclasses can answer the requests in the parent's interface, and they are all subtypes.
The risk is a subtype that answers differently from what callers expect. A made-up case: Shape.area() is expected to return a non-negative number. A BrokenShape that returns -1 for "unknown" would pass the compiler and break every caller that adds areas. The rule, which Level 2 calls substitutability, is that a subtype must keep the promises of its parent, not only its method names.
A habit that helps: write down in the interface's comment what each method promises, such as "never negative", "never null", "throws no checked exception". Each implementation must keep those promises.
Check yourself: 1. What does the compiler check about a subtype, and what does it not check? 2. Where should an interface's promises be written? 3. What does a client assume about every object of a type?