Sobes.tech
Junior — Middle

Which object-oriented programming principle relates to the Liskov substitution principle?

sobes.tech AI

Answer from AI

The Liskov Substitution Principle (LSP) relates to object-oriented programming principles and is closely connected to inheritance. It states that objects of a subclass should be interchangeable with objects of the superclass without violating the correctness of the program.

That is, if class B inherits from class A, then objects of class B should behave in such a way that they can be used in place of objects of class A without unexpected errors or changes in behavior.

This helps create class hierarchies where subclasses extend the functionality of base classes without breaking their contracts.

Example:

class Bird {
  void fly() {
    print('Bird is flying');
  }
}

class Sparrow extends Bird {
  @override
  void fly() {
    print('Sparrow is flying');
  }
}

// Violation of LSP if a subclass cannot fly
class Ostrich extends Bird {
  @override
  void fly() {
    throw Exception('Ostrich cannot fly');
  }
}

Here, Ostrich violates the Liskov principle because it cannot replace Bird without changing behavior.