Why is there an ability to override non abstract methods of base class

Question:

C++, PHP, Python and other OOP languages allow to override non-abstract methods of base class.

However, this ability allow to violate Liskov substitution principle. Because in such case base class can not be substituted in program with a derived class without changing program behavior.

Am I wrong?

Asked By: legale

||

Answers:

But this ability allow to violate Liskov substitution principle. Because in such case base class can not be substituted in program with a derived class without changing program behavior.

This is an incorrect characterization of the Liskov substitution principle. To be correct, change "without changing program behavior" to "without changing the correctness of the result" (see Wikipedia for a reference). The idea is not that the behavior is unchanged, but that the changed behavior is correct for the object in question. Different objects may have different behaviors that are considered correct, hence the need to override the non-abstract method. In fact, replacing one object with another might require a change in program behavior in order for the result to be correct.

For example, think about clicking things on this web page. The thing you click corresponds to the object, while the click corresponds to a call to that object’s onClick virtual function. What is the correct behavior in response to your click? It depends on the object. If the object is a link, the correct behavior is to open the link. If the object is this paragraph, the correct behavior is to ignore the click (assuming a simple click; a double-click might select a word). Different behaviors, but both are correct. It is correctness that the Liskov substitution principle calls for, and correctness might require program behavior to change depending on the object in question.

Answered By: JaMiT
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.