Skip to main content
InterviewHubPRO
Section Overview
Q4

Question 4 of 50

Part 1: Core SOLID Principles & Fundamentals (1 - 10)

8%
SOLID & OOP Principles (50 Qs)•Part 1: Core SOLID Principles & Fundamentals (1 - 10)

What is the Liskov Substitution Principle (LSP) and what is the classic Rectangle-Square violation?

junior Levelsolid-principlesCore SOLID Principles

In Simple Words: Subclasses must adhere to the behavioral contract of their parent class:

  • The Rectangle-Square Violation:
    • Square inherits from Rectangle.
    • In Square, setting width automatically sets height to maintain a square.
    • A function expecting a Rectangle sets width = 5 and height = 10 and expects area to be 50.
    • Passing Square produces area 100, silently violating mathematical assumptions and breaking caller code!
  • Rule: If a subtype cannot fulfill all invariants of the parent, use composition instead of inheritance.