it states that derived class must be substitutable for their base classes. which means that the subtypes must be replaceable for their super type references without affecting the program execution.
This principle was early described by Barbra Liskov in 1988.
When we were learning about object oriented programming, inheritance is usually described as an “is a” relationship, like If a penguin “is a” bird, then the
Penguin class should inherit from the
Bird class. The “is a” technique of describing inheritance relationship is simple and useful, but occasionally results in bad use of inheritance.
I’ll use the square and rectangle example to demonstrate the principle:
we have a Rectangle base Class that have two properties width and height , and subclass called Square that have the same two properties Height and Width and a method called SideLength that we use to set the values of height and width properties to make them equal.
The Liskov Substitution Principle is broken here, because the values of the Width and Height properties changed in the subclasses. Substitution of the Square with a Rectangle gives some unexpected results.
The height of the substituted ‘Rectangle’ is 6 and not the given 4. Since the behavior setting the Square property is different from the Rectangle, we can’t substitute the Square for a Rectangle.
A better design, following the Liskov Substitution Principle, is to make a base class Shape for both the Rectangle and Square descendant classes.
Substitution of the Square or Rectangle with the Shape class wont affect the values of Width and Height in both subclasses.
and as you see it will return the expected result.