Subtyping and Type Hierarchies
You'll learn how one type can safely substitute for another through subtype relationships, forming hierarchies that enable flexible and reusable code.
What Is Subtyping?
Subtyping defines a relation between types where values of one type (the subtype) can be used wherever values of another type (the supertype) are expected. If S is a subtype of T (written S <: T), then any S value can safely stand in for a T value.
Think of it like organizational roles: if every Manager is also an Employee, then anywhere you need an Employee, you can use a Manager—because managers have at least all the capabilities employees have, and possibly more.
Type Hierarchies
Types can form hierarchies through subtyping relationships. At the top might be a very general type (like Object or Any), with more specific types below. For example:
Integer <: Number <: AnyManager <: Employee <: Person
Each level down the hierarchy is more specific, carrying additional constraints or capabilities.
The Substitution Principle
The core rule is the Liskov Substitution Principle: a subtype must be usable wherever its supertype is expected without breaking program correctness. This means:
- A function accepting type
Tmust work correctly when given any subtype ofT - Subtypes can add new methods but cannot remove or weaken existing ones
- Return types in subtypes can be more specific, but parameter types cannot be more restrictive
This principle ensures type safety while allowing flexibility—you can write functions that work on general types and automatically work with more specific ones too.
Key Takeaway: Subtyping creates safe type hierarchies where more specific types can replace more general ones, enabling code reuse while preserving type safety through the substitution principle.