githubEdit

Liskov Substitution

Subtypes must be substitutable for their base types.

Explanation: A subclass should be able to replace its superclass without altering the correctness of the program.

Java Example

Bad Design (Violating LSP)

class Rectangle {
    int width, height;

    void setWidth(int width) {
        this.width = width;
    }

    void setHeight(int height) {
        this.height = height;
    }

    int getArea() {
        return width * height;
    }
}

class Square extends Rectangle {
    void setWidth(int width) {
        this.width = width;
        this.height = width; // Violates LSP
    }

    void setHeight(int height) {
        this.width = height;
        this.height = height; // Violates LSP
    }
}

Here, Square is a subclass of Rectangle, but it breaks LSP because changing the width also changes the height, making it behave differently from a rectangle.

Good Design (Following LSP)

Now, both Rectangle and Square can be used interchangeably without breaking behavior.


Python Example

Bad Design (Violating LSP)

👎 Problem: A Square should not behave like a Rectangle. Setting width also changes the height, breaking expected behavior.

Good Design (Following LSP)

👍 Fix: Now, Square and Rectangle can be used interchangeably without breaking behavior.

Last updated