Spis Treści
Some theory
The third principle that I will discuss in the series of articles on SOLID will be the Liskov substitution principle. This principle is directly related to the inheritance mechanism and its content is as follows:
Functions that use pointers or references to base classes must be able to use class objects that inherit base classes as well, without knowing exactly those objects.
Wikipedia
It looks scary, doesn't it? I think this principle can be presented a bit simpler and more intuitively:
Where you are using a base class, you should be able to use a class that inherits from it
The famous example with a square
The simplest and best demonstration of this principle is the example with calculating the area of a rectangle and a square. We create a base class of a rectangle with a method that calculates the area of the figure and a square class that inherits from the rectangle (after all, a square is a rectangle):
public class Rectangle {
protected int width;
protected int height;
public void setWidth(int width) {
this.width = width;
}
public void setHeight(int height) {
this.height = height;
}
public int calculateArea() {
return width * height;
}
}
public class Square extends Rectangle {
public void setWidth(int width) {
this.width = width;
this.height = width;
}
public void setHeight(int height) {
this.width = height;
this.height = height;
}
}
Now let's use our classes according to the code below and think about the results we will get:
public class Launcher {
public static void main(String[] args) {
//make operations using base class
Rectangle rectangle = new Rectangle();
rectangle.setWidth(5);
rectangle.setHeight(10);
System.out.println(rectangle.calculateArea());
//make operations using polymorphism
Rectangle rectangleSquare = new Square();
rectangleSquare.setWidth(5);
rectangleSquare.setHeight(10);
System.out.println(rectangleSquare.calculateArea());
//make operations using inherited class
Square square = new Square();
square.setWidth(5);
square.setHeight(10);
System.out.println(square.calculateArea());
}
}
If you have already analyzed the above code, you will surely notice that something is wrong here. While from the first equation we get the correct value of 50, then from the next equation we get the value 100 and again 100.
This is an example of breaking the Liskov substitution rule - code execution has different effects depending on the reference to the base class or child class. So again: The child class should not change the behavior of the base class.
Treść jest klarowna, dobrze zorganizowana i pełna przydatnych wskazówek. Autor doskonale wyjaśnia kluczowe zagadnienia. Może warto by dodać więcej przykładów praktycznych. Pomimo tego, tekst jest niezwykle edukacyjny i inspirujący.
Pingback: SOLID - podstawa programowania obiektowego – Wojciech Siwek
Comments are closed.