Understand Liskov Substitution Principle by example!

Tram Ho

What is Liskov Substitution Principle?

  • The principle defines that objects of a superclass shall be replaceable with objects of its subclasses without breaking the application.
  • The principle of opening and closing determines that the instances of the subclass can replace the parent class instance while ensuring the correctness of the program.

Take real examples?

We need to sum all integers in an array. A little more “modern” we need to sum the even numbers in this membrane for example. Hmmm!. Let’s start the project!

The first is to initialize 2 classes. Class SumCalculator

  • The Calculate () method to sum the numbers in the array. Class EvenNumbersSumCalculator inherits class SumCalculator
  • The Calculate () method to sum even numbers in an array (note: The new keyword is used here to indicate that the programmer is creating a new version of this method inside the subclass).

  • Now, let’s test these two functions:

  • The results of the program will be:

  • So this is fine then what =)). But we know that an object of a subtype can be assigned to a variable of its parent type , ie the base type can be used instead of the derived type (learn polymorphism). In this example we can store EvenNumbersSumCalculator as a SumCalculator variable.

  • Now the original 2 classes will fix a bit

  • Test the function to calculate the even total😃

  • The results of the program will be:

  • As we can see, we don’t get the expected results because our evenSum variable is of type SumCalculator, which is a higher order class (base class). This means that the Sum method from SumCalculator will be executed. So this is obviously not true, because our subclass does not act as a surrogate class for the superclass (not true for Liskov Substitution Principle).

Now it is time to apply Liskov Substitution Principle

  • At this time the original 2 classes will become.

  • Main function

  • Program results
  • The results of the program will be:

  • Whoa. We will have the same result ** 40 & 18. But it is important that we can store any subclass reference into a base class variable and the behavior will not change, which is the goal of Liskov Substitution Principle
Share the news now

Source : Viblo