Senior
What is the principle of Barbara Liskov (LSP)? Can you give an example of a violation?
sobes.tech AI
Answer from AI
The Liskov Substitution Principle (LSP) states that objects of a subclass should be interchangeable with objects of the superclass without affecting the correctness of the program. In other words, a subclass should extend the functionality of the base class without changing its behavior.
Example of violating LSP:
class Rectangle {
protected int width, height;
public void setWidth(int w) { width = w; }
public void setHeight(int h) { height = h; }
public int getArea() { return width * height; }
}
class Square extends Rectangle {
@Override
public void setWidth(int w) {
width = height = w;
}
@Override
public void setHeight(int h) {
width = height = h;
}
}
Here, Square inherits from Rectangle but changes the behavior of setWidth and setHeight methods such that the expectation that width and height can be changed independently is violated. If code works with Rectangle and expects to change width and height separately, passing a Square will alter the behavior, violating LSP.