Can you explain the main idea of Barbara Liskov's principle regarding substitution in object-oriented programming?
sobes.tech AI
Answer from AI
The Liskov Substitution Principle (LSP) states that objects of a subclass should be able to replace objects of the base class without affecting the correctness of the program. In other words, if class B inherits from class A, then wherever an object of A is used, an object of B should be able to be used instead, and the program should work correctly.
This means that a subclass should not violate the expectations set by the base class: it should not change the behavior of methods in a way that leads to errors or unexpected results. For example, a subclass should not weaken the preconditions of methods nor strengthen the postconditions.
Example in Python:
class Bird:
def fly(self):
print("Bird is flying")
class Sparrow(Bird):
def fly(self):
print("Sparrow is flying")
class Ostrich(Bird):
def fly(self):
raise Exception("Ostrich cannot fly")
# Violation of LSP: Ostrich cannot replace Bird because its fly method behaves differently
Here, the Ostrich class violates the Liskov principle because it does not support the behavior of the base class Bird.