Bird
Raised Fist0

Given a class hierarchy where a subclass overrides a method to strengthen postconditions, which pattern best ensures LSP compliance?

easy🔍 Pattern Recognition Q2 of Q15
OOP & Design Patterns - Liskov Substitution Principle - Subtype Behavioural Contract
Given a class hierarchy where a subclass overrides a method to strengthen postconditions, which pattern best ensures LSP compliance?
AContravariant parameter types allowing the subclass method to accept narrower input types.
BChanging method side effects in the subclass to alter observable state.
COverriding methods to throw new checked exceptions not declared in the superclass.
DCovariant return types allowing the subclass method to return a more specific type.
Step-by-Step Solution
Solution:
  1. Step 1: Understand LSP and method contracts

    LSP allows strengthening postconditions (e.g., return types) but forbids weakening preconditions (input parameters) or changing side effects.
  2. Step 2: Evaluate options

    B correctly describes covariant return types, which strengthen postconditions and comply with LSP. A is incorrect because contravariant parameters would weaken preconditions, violating LSP. C and D introduce behavioral changes that break substitutability.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Covariant returns strengthen postconditions without breaking LSP [OK]
Quick Trick: Covariant returns strengthen postconditions, safe under LSP [OK]
Common Mistakes:
MISTAKES
  • Confusing contravariant parameters as LSP-compliant
  • Ignoring side effect changes as LSP violations
Trap Explanation:
PITFALL
  • Candidates often mix covariance and contravariance rules, leading to wrong assumptions about LSP compliance.
Interviewer Note:
CONTEXT
  • Tests nuanced understanding of method signature variance under LSP.
Master "Liskov Substitution Principle - Subtype Behavioural Contract" in OOP & Design Patterns

2 interactive learning modes - each teaches the same concept differently

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More OOP & Design Patterns Quizzes