Junior — Middle
Explain the essence of the Liskov principle and its role in software development.
sobes.tech AI
Answer from AI
The Liskov Substitution Principle (LSP) is one of the five SOLID principles, which states that objects of a subclass should be interchangeable with objects of the superclass without affecting the correctness of the program.
This means that if class B inherits from class A, then anywhere an object of class A is used, an object of class B can be substituted, and the program will work correctly.
Role of the principle in development:
- Ensures reliability and predictability of inherited classes' behavior.
- Helps create extendable and maintainable systems.
- Prevents unexpected errors when replacing base classes with derived classes.
Example:
class Bird {
void fly() {
System.out.println("Bird is flying");
}
}
class Sparrow extends Bird {
// correctly inherits behavior
}
class Ostrich extends Bird {
@Override
void fly() {
throw new UnsupportedOperationException("Ostrich cannot fly");
}
}
Here, Ostrich violates the Liskov principle because it does not support the behavior of the base class Bird (the fly method). This can lead to errors if the code expects all birds to be able to fly.