-->

What does Liskov Substitution Principle preserve?

2019-08-20 12:50发布

问题:

This question already has an answer here:

  • What is an example of the Liskov Substitution Principle? 29 answers

As I've read the substitution of objects of a concrete type by instances of a subclass of that concrete type must preserve a program's correctness, a program's invariants.

I'd like to know what exactly is meant by correctness and invariants of a program?

回答1:

Let's say you have a class Animal and someone asks you what it's supposed to do, what it can be used for, and how you can judge whether or not it is correctly implemented. Imagine that you gave a complete and detailed answer that didn't leave anything out. Now...

If class Cow is a subclass of class Animal, then everything in your answer about Animal must also apply to Cow.