Liskov Substitution
What is it
Subclasses
should be substitutable for their base classes
.
An object (such as a class) may be replaced by a sub-object (such as a class that extends the first class) without breaking the program
- if
S
is a subtype ofT
, then objects of typeT
in a program may be replaced with objects of typeS
without altering any of the desirable properties of that program
When we use inheritance we assume that the child class inherits everything that the superclass has.
- The child class extends the behavior but never narrows it down.
class Test { static void getAreaTest(Rectangle r) { int width = r.getWidth(); r.setHeight(10); System.out.println("Expected area of " + (width * 10) + ", got " + r.getArea()); } public static void main(String[] args) { Rectangle rc = new Rectangle(2, 3); getAreaTest(rc); // squares test would fail Rectangle sq = new Square(); sq.setWidth(5); getAreaTest(sq); } }