Junior — Middle
Can you give an example of 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 affecting the correctness of the program.
Example in C#:
class Bird {
public virtual void Fly() {
Console.WriteLine("Bird is flying");
}
}
class Sparrow : Bird {
public override void Fly() {
Console.WriteLine("Sparrow is flying");
}
}
class Ostrich : Bird {
public override void Fly() {
throw new NotSupportedException("Ostrich cannot fly");
}
}
void MakeBirdFly(Bird bird) {
bird.Fly();
}
// Usage:
MakeBirdFly(new Sparrow()); // correct
MakeBirdFly(new Ostrich()); // violates LSP, as it throws an exception
In this example, the Ostrich class violates the Liskov Substitution Principle because it does not support the behavior of the base class Bird (the Fly method), throwing an exception. To adhere to LSP, you should either modify the class hierarchy or split interfaces so that subclasses are not forced to implement unsupported behavior.