Rajat's Notes

Personal knowledge based for Tech, Interviews and many more.

This project is maintained by im-Rajat

Liskov Substitution Principle

Bad Implementation :

public class Bird {
    public void fly() {}
}

public class Duck extends Bird {}

// The duck can fly because it is a bird, but what about this:

public class Ostrich extends Bird {}

// Ostrich is a bird, but it can't fly, Ostrich class is a subtype of class Bird, but it shouldn't be able to use the fly method, that means we are breaking the LSP principle.

Good Implementation :

public class Bird {}

public class FlyingBird extends Bird {
    public void fly() {}
}

public class Duck extends FlyingBird {}
public class Ostrich extends Bird {}