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
S
is a subtype of T
, then objects of type T
in a program may be replaced with objects of type S
without altering any of the desirable properties of that programWhen we use inheritance we assume that the child class inherits everything that the superclass has.
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); } }