Liskov Substitution Principle
This program demonstrates Liskov Substitution Principle.
Problem Statement
Write a Java program where subclass objects can replace superclass without issues.
Source Code
| 1 | class Bird { |
| 2 | void fly(){ System.out.println("Bird flies"); } |
| 3 | } |
| 4 | class Sparrow extends Bird { |
| 5 | void fly(){ System.out.println("Sparrow flies"); } |
| 6 | } |
| 7 | public class LSPExample { |
| 8 | public static void main(String[] args) { |
| 9 | System.out.println("Eduinq LSP Example"); |
| 10 | Bird b=new Sparrow(); |
| 11 | b.fly(); |
| 12 | } |
| 13 | } |
Program Output
Eduinq LSP Example Sparrow flies
Explanation
LSP states subclasses should be substitutable for superclass. - Sparrow can replace Bird without breaking behavior. - This ensures consistent polymorphism and reliability. Conclusion: Shows how to apply Liskov Substitution Principle.