Liskov Substitution Principle (LSP)

The Liskov Substitution Principle (LSP) is one of the five SOLID principles of object-oriented programming and design.

It was introduced by Barbara Liskov and states that objects of a superclass should be replaceable with objects of a subclass without affecting the correctness of the program. In other words, if a class S is a subclass of class T, then an object of class T should be replaceable with an object of class S without affecting the functionality of the program.


Now, let's consider an example in C# with a Truck and Lorry class.

   
  
public class Vehicle
{
    public virtual void Transport()
    {
        Console.WriteLine("Transporting...");
    }
}

public class Truck : Vehicle
{
    public override void Transport()
    {
        Console.WriteLine("Truck is transporting goods.");
    }
}

public class Lorry : Vehicle
{
    public override void Transport()
    {
        Console.WriteLine("Lorry is transporting cargo.");
    }
}


class Program
{
    static void Main()
    {
        Vehicle truck = new Truck();
        Vehicle lorry = new Lorry();

        PerformTransport(truck);
        PerformTransport(lorry);
    }

    static void PerformTransport(Vehicle vehicle)
    {
        // Liskov Substitution Principle in action
        vehicle.Transport();
    }
}
  


In this example, Truck and Lorry are subclasses of the Vehicle class. Both Truck and Lorry override the Transport method, providing their own specific implementation. The PerformTransport method takes a Vehicle parameter, and you can pass instances of both Truck and Lorry to it without affecting the correctness of the program. This adheres to the Liskov Substitution Principle.

It's important to note that the overridden method in the subclasses should not violate the contracts defined by the base class. In this case, both Truck and Lorry maintain the contract by providing their own transportation implementations.

Comments