- Introduced By Barbara Liskov in a 1987 keynote address titled ‘Data abstraction and hierarchy’
- Core Concept: Objects of a superclass can be replaced with objects of a subclass without breaking the program
- Fundamental Principle: Guarantees semantic interoperability of types in a hierarchy, particularly object types
Explanation
The principle states that a derived class should be substitutable for its base class without affecting the correctness of the program. Meaning that objects of a superclass should be replaceable with objects of the subclass without affecting the ‘correctness’ of the program and without causing errors and unexpected behavior.
Key aspects of LSP include:
- No new exceptions should be thrown by derived class methods
- Preconditions can be weakened but not strengthened in subtypes
- Postconditions can be strengthened but not weakened in subtypes
- Base class invariants must be preserved in the subclass
- Objects should only be modified through their methods (encapsulation)
- New methods in subtypes may allow state changes not permissible in the supertype
- The principle is illustrated with an example: if Cat is derived from Animal, the system should be able to use a Cat object wherever an Animal object is expected