Video in progress

Explain the Liskov principle with the rectangle and square example.

In math a square is a rectangle, but in code, if you make Square extends Rectangle and setWidth changes both sides, code that expects a rectangle gets the wrong result. LSP says: a child class must not break the promises of the parent class.

📖 Answer

public class Rectangle {
    private int width;
    private int height;

    public void setWidth(int width)   { this.width = width; }
    public void setHeight(int height) { this.height = height; }
    public int getWidth()  { return width; }
    public int getHeight() { return height; }
    public int area() { return width * height; }
}

public class Square extends Rectangle {
    @Override public void setWidth(int side)  { super.setWidth(side); super.setHeight(side); }
    @Override public void setHeight(int side) { super.setWidth(side); super.setHeight(side); }
}

// a simple test written for Rectangle
void resize(Rectangle shape) {
    shape.setWidth(5);
    shape.setHeight(4);
    // prints 20 for a Rectangle, but 16 for a Square
    System.out.println(shape.area());
}

The resize method trusted the Rectangle contract: "width and height change independently". Square broke that promise.

You can tell LSP is violated when:

  • a child method throws an exception the parent method doesn't (UnsupportedOperationException);
  • the child tightens the preconditions or weakens the guarantees on the result;
  • if (x instanceof Square) shows up in calling code.

Solutions: make both separate implementations of a common Shape interface, or make the objects immutable. With no mutating setters, the conflict disappears too.