Course contentsShow
← Software Engineering
Lesson 209 of 1,9336. SOLID PrinciplesFree lesson

Behavioral Subtyping and Contracts

Subtypes must honor the behavioral contract of their base types, including preconditions, postconditions, and invariants.

Behavioral Subtyping and Contracts

What you'll learn: How subtypes must honor the promises (contracts) made by their base types, not just match their structure.

The Contract Concept

When a base type defines methods, it's not just specifying what the method signature looks like—it's making promises about how those methods behave. Think of it like a warranty: if a base class promises "this method will never return negative numbers," any subtype must honor that same guarantee. This is called behavioral subtyping.

The Three Contract Elements

A behavioral contract has three parts:

Preconditions are what must be true before a method runs. For example, "input must be positive." Subtypes can weaken (relax) preconditions but never strengthen them—you can accept more inputs than your parent, not fewer.

Postconditions are what must be true after a method completes. For example, "return value is sorted." Subtypes must maintain or strengthen postconditions—you must deliver at least what your parent promised, or more.

Invariants are conditions that must always hold true for the object's state. Subtypes must preserve all parent invariants throughout their lifetime.

Why This Matters

If a subtype violates its parent's contract, code that depends on the parent's behavior will break when you substitute the child. Imagine a BankAccount that promises "balance never goes negative," but a subtype UnrestrictedAccount allows negative balances. Any code checking the parent's contract will fail unexpectedly.

This is the heart of the Liskov Substitution Principle—structure isn't enough; behavior must be compatible too.

Key Takeaway: Subtypes must honor their parent's behavioral promises: weaken or maintain preconditions, strengthen or maintain postconditions, and always preserve invariants.