SOLID Principles: Liskov Substitution Principle (LSP)

Image for post
Image for post
  • A subclass should behave in such a way that it will not cause problems when used instead of the superclass.
  • LSP is a definition of a subtyping relation, called strong behavioral subtyping.
  • if S is a subtype of T, then objects of type T may be replaced with objects of type S without altering the desirable properties of the program.
  • Example:

Bad Example of LSP:

The duck can fly because it is a bird, But what about this:

Ostrich is a bird, But it can’t fly, Ostrich class is a subtype of class Bird, But it can’t use the fly method, that means that we are breaking the LSP principle.

Good Example of LSP:

ability to replace any instance of a parent class with an instance of one of its child classes without negative side effect.

continuo to the rest of SOLID

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store