Liskov Substitution Principle

Liskov Substitution Principle enables you to replace objects of a parent class(Bird) with objects of a subclass(Eagle,Penguin) without breaking the application.

Liskov Substitution Principle extends the open/closed Principle.


public class Bird {
    private int wings;
    private int health;

    public Bird(int wings, int health) {
        this.wings = wings;
        this.health = health;
    }

    private booelan fly() {
        if (health > 0 && wings==2) {
             System.out.println("The bird is flying.");
            return true;
        } else {
            System.out.println("The bird cannot fly.");
           return false;
        }
    }

     // Getters and setters for health and wings can be added here if needed
}

public class BirdAnalysisClient {
    // This method accepts a Bird object or any of its subtypes 
    // (e.g., Eagle, Penguin
    public void crossLake(Bird bird) {
        if (bird.canFly()) {
            System.out.println("The bird can cross the lake.");
        } else {
            System.out.println("The bird cannot cross the lake.");
        }
    }
}
// Test works fine no issue . Looks good .
public class BirdAnalysisTester {
    public static void main(String[] args) {
        BirdAnalysisClient client = new BirdAnalysisClient();

        Bird genericBird = new Bird(1,2);
        client.crossLake(genericBird);
    }
}

public class Eagle extends Bird {

public Eagle(boolean isHealthy, int wings) { 
    super(isHealthy, wings);
 }

}

// Logic works fine no issue.
public class BirdAnalysisTester {
    public static void main(String[] args) {
        BirdAnalysisClient client = new BirdAnalysisClient();

        Bird genericBird = new Eagle(1,2);
        client.crossLake(genericBird);
    }
}
// Liskov Substitution priniciple not followed .
// This child class will break application on use instead of parent class.
public class Penguin extends Bird {

    public Penguin(int wings, int health) {
        super(wings, health);        
    }

    @Override 
    public boolean canFly() { 
    throw new UnsupportedOperationException("Penguins cannot fly"); 
    } 
}

// Logic works fails, code throws an error . 

public class BirdAnalysisTester {
    public static void main(String[] args) {
        BirdAnalysisClient client = new BirdAnalysisClient();

        Bird genericBird = new Penguin(1,2);
        client.crossLake(genericBird);
    }
}
0
Subscribe to my newsletter

Read articles from Palanivel SundaraRajan GugaGuruNathan directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Palanivel SundaraRajan GugaGuruNathan
Palanivel SundaraRajan GugaGuruNathan

Hi , thanks for stopping by! I am full-stack developer and I'm passionate about making complex concepts clear through code and visuals. After all, a picture (and a code snippet) is worth a thousand words! I hope you enjoy my blog.