Quote from Wikipedia: Inheritance, even in programming languages ​​that support the use of inheritance as a mechanism that ensures polymorphism of subtypes, does not guarantee the behavioral polymorphism of subtypes; see: “Principle of Substitution” by Barbara Liskov.

What is meant by behavioral polymorphism of subtypes here? How to correctly and concisely answer this question?

I understand it this way: Again, a quote from Wikipedia: In simpler words, we can say that the behavior of inherited classes should not contradict the behavior specified by the base class, that is, the behavior of inherited classes should be expected for code that uses a variable of the base type. It follows from this that inheritance does not protect the programmer from the fact that he can change the behavior in the redefined method. For example, the add() method in the base class adds an object, and you can easily override it and this method will delete an object. Preserving the behavior of the base method is behavioral polymorphism.

Am I right?

    1 answer 1

    You understand correctly. Behavioral polymorphism is when a child class does not change the behavior of the parent. For example, imagine a situation, we have a class

     class Rechtangle { protected int width; protected int height; public void setWidth(int w) { this.width = w; } public void setHeight(int h) { this.height = h; } public int area() { return width * height; } } 

    And we add a new class "Square", how it differs from a rectangle, in that its sides should change simultaneously, if we change the height, then the width should change, an example

     class Square extends Rechtangle { @Override public void setWidth(int w) { this.width = w; this.height = w; } @Override public void setHeight(int h) { this.width = h; this.height = h; } } 

    Now imagine that some programmer wrote the following code

     void mainProcedure(Rechtangle figure) { figure.setWidth(5); figure.setHeight(3); assert figure.area() == 15; } 

    Let's now call this function with the implementation of the square

    mainProcedure(new Square())

    AssertionError will be thrown, here's a clear violation of the LSP principle and behavioral polymorphism. Because in fact, a square is not a rectangle and the developer of the mainProcedure procedure mainProcedure not expect that he could get a square masquerading behind the rectangle. The programmer who wrote the procedure is right. He checked the contract which had to be respected by a rectangle, but was broken by a square.

    • Comments are not intended for extended discussion; conversation moved to chat . - Yuriy SPb