Can you explain the meaning of the letter L in the SOLID principles?
sobes.tech AI
Answer from AI
The letter L in the SOLID principles stands for Liskov Substitution Principle. This principle states that objects of a subclass should be interchangeable with objects of the superclass without affecting the correctness of the program.
In simpler terms, if class B inherits from class A, then anywhere an object of class A is expected, an object of class B can be used, and the program will work correctly.
This is important for maintainability and extensibility of the code, so that adding new subclasses does not break the logic.
Example in Java:
class Bird {
void fly() {
System.out.println("Bird is flying");
}
}
class Sparrow extends Bird {
@Override
void fly() {
System.out.println("Sparrow is flying");
}
}
class Ostrich extends Bird {
@Override
void fly() {
throw new UnsupportedOperationException("Ostrich can't fly");
}
}
Here, Ostrich violates the Liskov principle because it cannot replace Bird without changing behavior (the fly method throws an exception). To adhere to the principle, the class hierarchy should be reconsidered.