Objects of a superclass should be replaceable with objects of a subclass without affecting the program.
// Violating LSP
public class Bird {
public virtual void Fly() {
Console.WriteLine("Bird is flying");
}
}
public class Ostrich : Bird {
public override void Fly() {
throw new NotImplementedException("Ostrich can't fly");
}
}
// Following LSP
public abstract class Bird {
public abstract void Move();
}
public class Sparrow : Bird {
public override void Move() {
Console.WriteLine("Sparrow is flying");
}
}
public class Ostrich : Bird {
public override void Move() {
Console.WriteLine("Ostrich is running");
}
}
Liskov Substitution Principle (LSP)
Explanation:
Objects of a superclass should be replaceable with objects of a subclass without affecting the program.
Real-World Example:
If a bird can fly, a sparrow (subclass) should also fly.
C# Implementation: