Halo semuanya, nama saya Konstantin. Saya berkembang di Jawa di Tinkoff.ru dan cinta SOLID. Dalam artikel ini, kami akan merumuskan prinsip substitusi Lisk, menunjukkan hubungannya dengan prinsip Terbuka-Tertutup, mempelajari cara membentuk hierarki warisan dengan benar, dan menjawab pertanyaan filosofis apakah persegi adalah persegi panjang.

, , , .
-. , , , . . ( LSP) โ , - . โ , LSP, -.
:
, , -, .
:
, : o1 S o2 T, P, T, P , o2 o1, S โ T.
, LSP, , , , . -, , .
LSP
, :
void drawShape(Shape shape) {
   if (shape instanceof Square) {
       drawSquare((Square) shape);
   } else {
       drawCircle((Circle) shape);
   }
}
. Shape, , drawCircle, , โ .
drawShape Shape. , , Shape , . Shape, -.
, LSP . , , . :
public class Rectangle {
    private int width;
    private int height;
    public int getWidth() {
        return width;
    }
    public void setWidth(int width) {
        this.width = width;
    }
    public int getHeight() {
        return height;
    }
    public void setHeight(int height) {
        this.height = height;
    }
    public int perimeter() {
        return 2 * height + 2 * width;
    }
}
. , . , , , , , โ Square. ?
, ยซยป (ISA). , , ISA , , .
โ . , ISA. , Square Rectangle. , , , , .
, Square height width, , side, . , ( , , ), . , Square setWidth setHeight. , :
    @Override
    public void setWidth(int width) {
        super.setWidth(width);
        super.setHeight(width);
    }
    @Override
    public void setHeight(int height) {
        super.setHeight(height);
        super.setWidth(height);
    } 
Square . . Square. . , , , , .
, Rectangle :
public class RectangleTest {
    @Test
    public void perimeter() {
        Rectangle rectangle = new Rectangle();
        rectangle.setHeight(5);
        rectangle.setWidth(7);
        int result = rectangle.perimeter();
        assertEquals(24, result);
    }
} 
, Square . Square ISA Rectangle, , Rectangle Square. , :
public class RectangleTest {
    @Test
    public void perimeter() {
        Rectangle rectangle = initRectangle();
        rectangle.setHeight(5);
        rectangle.setWidth(7);
        int result = rectangle.perimeter();
        assertEquals(24, result);
    }
    protected Rectangle initRectangle() {
        return new Rectangle();
    }
}
public class SquareTest extends RectangleTest {
    @Override
    protected Rectangle initRectangle() {
        return new Square();
    }
}
, SquareTest.perimeter , perimeter 24, , 28. : , , ? โ . , Rectangle, Square. Square Rectangle , Rectangle ( ) , Rectangle Square. Square โ Rectangle, LSP .
โ ?
โ , , , Square โ Rectangle. , Square Rectangle. , .
, ISA . , , . , .
. โ , , . , , .
?
: . . , .
, , , , , . Shape Square Rectangle.
, . , . Quadrangle , , , , . .
- , , .
, , . , , , , , -.
1996 โ The Liskov Substitution Principle. . , , C++. , , LSP .