ProgrammingHardProduct-company placement · GATE CS
A drawing program uses the Visitor pattern: Shape has accept(Visitor v), and Circle implements it as v.visit(this). Visitor has overloads visit(Circle) and visit(Square). Why can't client code holding a Shape s simply call v.visit(s)?
- A. visit methods must be static, so they need an instance to call them
- B. Visitor objects cannot be passed to shapes directly
- C. It would work, but accept() makes it faster
- D. Overloads are chosen from the static type Shape at compile time, so no visit(Circle) is selected; accept() adds a second, virtual dispatch on the shape's real type
Correct answer: D. Overloads are chosen from the static type Shape at compile time, so no visit(Circle) is selected; accept() adds a second, virtual dispatch on the shape's real type
Java and C++ dispatch virtually only on the receiver. Inside Circle.accept, this has static type Circle, so the right overload is fixed at compile time: two dispatches (on the shape, then on the visitor) give double dispatch. v.visit(s) would need a visit(Shape) overload and lose the type.
More OOP with C++ and Java questions
- How many of these statements about Java (9 or later) are correct? 1. An interface can declare instance fields. 2. An abstract class can…
- A UI component registers itself as an observer of a long-lived global EventBus when it is created but never unregisters. Screens using…
- A vending machine object behaves differently when Idle, HasCoin or Dispensing, and each state object decides which state comes next. A…
- Account.withdraw(amount) works for any amount up to the balance. A subclass FixedDeposit overrides it to throw an exception unless the…
- Which call violates the Law of Demeter (talk only to your immediate collaborators) inside an OrderService method that receives an Order…
- How many of these statements about Java methods are correct? 1. A final method can be overloaded in a subclass. 2. A static method can be…