DEV Community

Adam Roynon
Adam Roynon

Posted on

Liskov Substitution Principle

The Liskov Substitution Principle is a component of The SOLID Principles which helps you create maintainable and extensible code. This principle states that any class should be able to be substituted for any of its subclasses without any issues. This basically just means that if you have a parent class and a child class you should be able to use the child class in any place where the parent is used without your program blowing up in errors.

The below code snippets shows a very simple piece of code. First, a User object is created called 'john'. We pass the value "John" into the constructor of the class and then print out the value from the 'getName' method to the console. This basic example will effectively set the passed in value to a variable and then print out the variable to the console.

public class Main {

  public static void main(String[] args){
    User john = new User("John");
    System.out.println(john.getName());
  }

}
Enter fullscreen mode Exit fullscreen mode

The code below looks exactly the same to the above code snippet. The only difference here is that we have changed the concrete implementation class to "Person". Other than that the code should function exactly the same. We are assuming in this example that the Person class inherits from the User class, it is a child of the User class. This is a prime example of the Liskov Substitution Principle, the subclass can be used instead of the base class and the code still makes sense and still executes.

public class Main {

  public static void main(String[] args){
    User john = new Person("John");
    System.out.println(john.getName());
  }

}
Enter fullscreen mode Exit fullscreen mode

The Liskov Substitution Principle is a simple principle to understand and a simple concept to understand. It is important to understand that it is a one way track. Any subclass can replace any usage of its base class like shown above. However, the reverse is not true. You cannot replace a usage of a subclass with a base class. Usually, a subclass adds functionality or extends from a base class, therefore, replacing a usage of a subclass with a baseclass does not make sense as the base class does not have the added functionality.

This post was originally published on https://acroynon.com

Top comments (0)