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?
- A. Open/Closed Principle
- B. Interface Segregation Principle
- C. Dependency Inversion Principle
- 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
- A Department has Professors who continue to exist if the department is closed, while a House is made of Rooms that cannot exist without…
- What is printed? java // static methods of the main class: static void p(Object o) { System.out.print("O"); } static void p(String s) {…
- What is printed? java Map<String, Integer> m = new TreeMap<>(Map.of("a", 1, "b", 2)); for (Map.Entry<String, Integer> e : m.entrySet())…
- What is printed? java Map<String, Integer> m = new TreeMap<>(Map.of("a", 1, "b", 2, "c", 3)); m.keySet().remove("b")…
- Which statement about the protected modifier is true in Java but NOT in C++?
- What is printed? java // file a/P.java package a; public class P { void f() { System.out.print("P"); } // package-private public void…