SOLID Principles: Liskov Substitution Principle (LSP)

Hussein Reda
Oct 25, 2020

--

  • 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:

public class Bird{
public void fly(){}
}
public class Duck extends Bird{}

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

public class Ostrich extends Bird{}

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:

public class Bird{
}
public class FlyingBirds extends Bird{
public void fly(){}
}
public class Duck extends FlyingBirds{}
public class Ostrich extends Bird{}

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

--

--