DEV Community

Cover image for SOLID in Software Development - 3
ajay-8192
ajay-8192

Posted on

SOLID in Software Development - 3

Liskov Substitution Principle (LSP)

The Liskov Substitution Principle (LSP) states that objects of a superclass should be replaceable with objects of its subclasses without breaking the application. This means that subclasses should be able to fulfill the same contract as their superclass without introducing any unexpected behavior.

Here is an example of how the LSP can be violated:

public class Rectangle {
    private double length;
    private double width;

    public Rectangle(double length, double width) {
        this.length = length;
        this.width = width;
    }

    public double getArea() {
        return length * width;
    }
}

public class Square extends Rectangle {
    public Square(double side) {
        super(side, side);
    }

    @Override
    public double getArea() {
        return side * side * side; // This violates the LSP because it changes the behaviour of the `getArea` method
    }
}
Enter fullscreen mode Exit fullscreen mode

The Square class is a subclass of the Rectangle class. However, the getArea method of the Square class violates the LSP because it changes the behaviour of the getArea method of the Rectangle class. This means that if we substitute an object of the Square class for an object of the Rectangle class, then the program may break.

A better way to design this code would be to have the Square class return the correct area:

public class Rectangle {
    private double length;
    private double width;

    public Rectangle(double length, double width) {
        this.length = length;
        this.width = width;
    }

    public double getArea() {
        return length * width;
    }
}

public class Square extends Rectangle {
    public Square(double side) {
        super(side, side);
    }

    @Override
    public double getArea() {
        return side * side;
    }
}
Enter fullscreen mode Exit fullscreen mode

This code follows the LSP because the getArea method of the Square class does not change the behaviour of the getArea method of the Rectangle class.

***** More to Part 4 *****
**** 💻ALL THE BEST💻 ****

Top comments (0)