Give an example of LSP compliance
An example of LSP compliance is a situation where a subclass extends the parent's behavior without violating its contract, and can fully substitute for the base class in client code.
Below is a correct example: the base class describes a notification interface, and subclasses implement different ways of sending it.
Base class (contract)
class Notifier:
def send(self, message: str):
raise NotImplementedErrorSubclasses that follow LSP
class EmailNotifier(Notifier):
def send(self, message: str):
print(f"Sending email: {message}")
class SmsNotifier(Notifier):
def send(self, message: str):
print(f"Sending SMS: {message}")Why this follows LSP:
- The subclasses do not change the meaning of the
send()method They simply implement it in their own way. The base contract: "send a message". Both subclasses follow this contract. - The subclasses do not tighten input restrictions The method accepts any string - both Email and SMS accept any string.
- The subclasses do not weaken the guarantees of the result The base class's promise: "the send operation is performed". Both implementations fulfill this.
- There is no need to check the type
Client code:
def notify(notifier: Notifier, msg):
notifier.send(msg)Any subclass can be substituted in:
notify(EmailNotifier(), "Hello!")
notify(SmsNotifier(), "Hello!")And the program will work correctly and predictably, with no changes.
- Invariants are not violated The base class has no state at all, so descendants cannot break anything.
Summary
The EmailNotifier and SmsNotifier classes fully preserve the contract of Notifier, do not change the meaning of the behavior, and can safely be used wherever the base type is expected - this is exactly what correct LSP compliance looks like.
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.