Category : SOLID | Sub Category : SOLID Principles | By Prasad Bonam Last updated: 2024-01-10 09:45:03 Viewed : 178
The Liskov Substitution Principle (LSP) states that objects of a superclass should be replaceable with objects of a subclass without affecting the correctness of the program. In other words, if a class S is a subclass of class T, an object of class T should be replaceable with an object of class S without affecting the functionality of the program.
Here is a simple example in Java to illustrate the Liskov Substitution Principle:
javaclass Shape {
int area() {
return 0; // Default implementation for the sake of example
}
}
class Rectangle extends Shape {
int width;
int height;
Rectangle(int width, int height) {
this.width = width;
this.height = height;
}
@Override
int area() {
return width * height;
}
}
class Square extends Shape {
int side;
Square(int side) {
this.side = side;
}
@Override
int area() {
return side * side;
}
}
class AreaCalculator {
int calculateArea(Shape shape) {
return shape.area();
}
}
In this example, Rectangle
and Square
are subclasses of Shape
. They both override the area
method to calculate the area based on their specific shapes. The AreaCalculator
class takes a Shape
as a parameter to calculate the area, adhering to the Liskov Substitution Principle.
Now, you can use instances of Rectangle
and Square
interchangeably in the AreaCalculator
without affecting the correctness of the program:
javapublic class Main {
public static void main(String[] args) {
AreaCalculator calculator = new AreaCalculator();
Rectangle rectangle = new Rectangle(5, 10);
Square square = new Square(5);
int rectangleArea = calculator.calculateArea(rectangle);
int squareArea = calculator.calculateArea(square);
System.out.println("Rectangle Area: " + rectangleArea);
System.out.println("Square Area: " + squareArea);
}
}
In this way, the Liskov Substitution Principle is maintained because objects of the Rectangle
and Square
subclasses can replace objects of the Shape
superclass without causing issues in the programs functionality.