Junior — Middle
What attracted you to learn the C# programming language and why did you decide to choose it for your projects?
sobes.tech AI
Answer from AI
The Liskov Substitution Principle (LSP) states that objects of a subclass should be replaceable with objects of the superclass without affecting the correctness of the program.
In iOS, for example, if there is a base class Bird with a method fly(), and a subclass Penguin that cannot fly, replacing Bird with Penguin would violate LSP if fly() is called.
A correct approach is to define an interface or a separate class for flying birds, e.g., FlyingBird, and implement fly() only in those classes. Then, Penguin inherits from Bird but not from FlyingBird. This way, objects of FlyingBird can be used safely without breaking the principle.
class Bird {
func eat() {
print("Bird is eating")
}
}
protocol FlyingBird {
func fly()
}
class Sparrow: Bird, FlyingBird {
func fly() {
print("Sparrow is flying")
}
}
class Penguin: Bird {
// Does not implement fly()
}
This approach ensures safe substitution and adheres to LSP.