Subtypes must be substitutable for their base types.

Example: Consider a scenario with a base class Bird and a derived class Penguin.

// Violation of LSP
public class Bird {
    public void fly() {
        System.out.println("Flying");
    }
}

public class Penguin extends Bird {
    @Override
    public void fly() {
        throw new UnsupportedOperationException("Penguins can't fly");
    }
}

// Following LSP
public class Bird {
    public void move() {
        System.out.println("Moving");
    }
}

public class Penguin extends Bird {
    @Override
    public void move() {
        System.out.println("Swimming");
    }
}

public class Sparrow extends Bird {
    @Override
    public void move() {
        System.out.println("Flying");
    }
}

In this case, Penguin does not override fly because it doesn’t make sense for it. Instead, both Penguin and Sparrow override move, which can be either flying or swimming, respecting LSP.

Previous: Open/Closed Principle (OCP)

Next: Interface Segregation Principle (ISP)

SOLID


Leave a Reply

Your email address will not be published. Required fields are marked *