The Liskov Substitution Principle (LSP) is one of the five SOLID principles of object-oriented programming and states that objects of a derived class should be able to replace objects of the base class without affecting the correctness of the program. In other words, if a class A is a subtype of class B, you should be able to use an object of class A wherever an object of class B is expected, and the program should still work correctly.
Here's an example in Python to illustrate the Liskov Substitution Principle:
python
class Bird:
def fly(self):
pass
class Sparrow(Bird):
def fly(self):
print("Sparrow is flying")
class Ostrich(Bird):
def fly(self):
print("Ostrich cannot fly")
def make_bird_fly(bird):
bird.fly()
# Using Liskov Substitution Principle
sparrow = Sparrow()
ostrich = Ostrich()
make_bird_fly(sparrow) # Output: Sparrow is flying
make_bird_fly(ostrich) # Output: Ostrich cannot fly
In this example:
We have a base class
Birdwith aflymethod that doesn't do anything.We have two derived classes,
SparrowandOstrich, both of which inherit from theBirdclass and provide their own implementations of theflymethod.The
make_bird_flyfunction takes an argument of typeBirdand calls itsflymethod.We can use the Liskov Substitution Principle to substitute instances of
SparrowandOstrichfor aBirdobject in themake_bird_flyfunction. This demonstrates that objects of derived classes can be used interchangeably with objects of the base class without affecting the correctness of the program.
The key takeaway here is that both Sparrow and Ostrich are subclasses of Bird, and they can be used in a way that adheres to the Liskov Substitution Principle, allowing us to write more flexible and extensible code.
Comments
Post a Comment