by BehindJava

What is Liskov Substitution Principle in SOLID Design Principles of Object Oriented Programming

Home » java » What is Liskov Substitution Principle in SOLID Design Principles of Object Oriented Programming

Liskov Substitution Principle

Objects in a program should be replaceable with instances of their sub class without changing the behavior of program.

Example: Lets say you have a class A with a method named xyz(), we have another class B that extends A and overriding the same xyz() method in the class A.

class A{
    public void xyz(){
        //code
    }
}
class B extends A{
    @Override
    public void xyz(){
        //code
    }
}

Now we have class C with the method ace() with the method parameter as instance of class A.

class C{
    public void ace(A a){
        //code
    }
}

What Liskov Substitution principle says in the above example is , The input parameter you pass in class C can be the object of class A and object of class B and you may have doubt of why class B i.e., because class B is a sub class of class A. It has all the property of A and it has some additional properties of its own.

So using B’s object in place of A should be fine, else B is modifying some properties of A which can result in a possible bug.