Sobes.tech
Junior — Middle

Can you give an example demonstrating the Liskov substitution principle in object-oriented programming?

sobes.tech AI

Answer from AI

The Liskov Substitution Principle (LSP) states that objects of a subclass should be interchangeable with objects of the superclass without violating the correctness of the program.

Example:

// Superclass
class Bird {
    void fly() {
        System.out.println("Bird is flying");
    }
}

// Subclass that correctly extends behavior
class Sparrow extends Bird {
    @Override
    void fly() {
        System.out.println("Sparrow is flying");
    }
}

// Violation of LSP
class Ostrich extends Bird {
    @Override
    void fly() {
        throw new UnsupportedOperationException("Ostrich can't fly");
    }
}

// Usage
void makeBirdFly(Bird bird) {
    bird.fly(); // It is expected that the bird can fly
}

// Passing Ostrich will cause fly() to throw an exception, violating LSP.

To adhere to LSP, it is better to separate the hierarchy:

interface Flyable {
    void fly();
}

class Bird {}

class Sparrow extends Bird implements Flyable {
    public void fly() { System.out.println("Sparrow is flying"); }
}

class Ostrich extends Bird {
    // Does not implement Flyable, as it cannot fly
}

This way, subclass objects can be used without unexpected behavior.