ProgrammingHardProduct-company placement · Java

Square extends Rectangle and overrides setWidth and setHeight so that both always change together. Client code written for Rectangle does r.setWidth(5); r.setHeight(4); and expects area 20, but gets 16 for a Square. Which principle is violated?

  1. A. Open/Closed Principle
  2. B. Interface Segregation Principle
  3. C. Dependency Inversion Principle
  4. D. Liskov Substitution Principle

Correct answer: D. Liskov Substitution Principle

LSP requires that a subtype can be used wherever its base type is expected without breaking the base type's guarantees; independent width and height are part of Rectangle's contract, which Square breaks.

More OOP with C++ and Java questions

Exams that ask this topic