Junior — Middle
Could you provide an example of using the Liskov principle in practical code or a system?
sobes.tech AI
Answer from AI
The Liskov Substitution Principle states that objects of a subclass should be interchangeable with objects of the superclass without affecting the correctness of the program.
Example in Dart (Flutter):
abstract class Bird {
void fly();
}
class Sparrow implements Bird {
@override
void fly() {
print('Sparrow is flying');
}
}
class Ostrich implements Bird {
@override
void fly() {
throw Exception('Ostrich cannot fly');
}
}
void makeBirdFly(Bird bird) {
bird.fly();
}
void main() {
makeBirdFly(Sparrow()); // Works correctly
makeBirdFly(Ostrich()); // Violates the Liskov principle
}
In this example, the Ostrich class violates the Liskov principle because it cannot correctly replace Bird (it cannot fly). To adhere to the principle, it is better to separate interfaces, for example, by defining an interface for flying birds.