Skip to main content

Liskov Substitution Principle (LSP)

 Liskov Substitution Principle can be stated as: A type must be substitutable by its subtypes without altering the correctness of the application.

To make it easier let's start with an example. See the image below:

As you can see there is an interface IAnimal that defines two methods, speak() and sleep(). The IAnimal interface is implemented by two classes Parrot and Elephant. So far, so good but let's say that we should include ants in the application. To incorporate this change create an additional class called Ant that implements IAnimal. Since ants do not speak once you implement the interface the code would look something like this:

@Override

    public void speak() {

        throw new UnsupportedOperationException("Not supported yet."); 

    }

Now we can see a problem that might cause errors in the application. To correct this you can split the IAnimal interface into two. IAnimalSpeak and IAnimalSleep. The modified design is shown below.



The methods of IAnimal are split into two separate interfaces: IAnimalSpeak and IAnimalSleep. The IAnimalSpeak contains the method speak() and the IAnimalSleep contains the sleep() method.

To begin with, this example lets create the two interfaces, IAnimalSpeak and IAnimalSleep including the corresponding methods.


public interface IAnimalSpeak {
    public void speak();
    
}

public interface IAnimalSleep {
    public void sleep();
}

Now let's build the Elephant, Parrot, and Ant, classes.
public class Elephant implements IAnimalSleep, IAnimalSpeak{

    @Override
    public void speak() {
        System.out.println("bahruuuuuuhhhhaaaaa");
    }
    
    @Override
    public void sleep() {
        System.out.println("elephant sleeping...");
    }
    
}

public class Parrot implements IAnimalSleep, IAnimalSpeak{

    @Override
    public void speak() {
        System.out.println("AAAWK");
    }

    @Override
    public void sleep() {
        System.out.println("Parrot sleeping...");
    }
}

public class Ant implements IAnimalSleep {

    @Override
    public void sleep() {
        System.out.println("Ant sleeping...");
    }
    
}

As you can see Elephant and Parrot classes implements the interfaces IAnimalSleep and AnimalSpeak and both of them have the methods speak() and talk(). Besides the class Ant only implements the interface IAnimalSleep and has the method sleep().

Reference

Joshi, B. (2016b). Beginning SOLID Principles and Design Patterns for ASP.NET Developers (English Edition) (1st ed.). Apress.

Comments