What does double dispatch mean in the Visitor pattern, and how does it let a program run different logic per concrete type without any instanceof checks?
Double dispatch is two separate method-resolution steps happening back to back. The first dispatch is ordinary runtime polymorphism: calling accept() on an object typed as the general interface resolves, at runtime, to that object's real concrete type's implementation -- for example, PDFDocument's accept(), not some generic version. The second dispatch happens inside that accept() method, where the call is visitor.visit(this): because the compiler statically knows, at that exact line, that this is a PDFDocument, it selects the visit(PDFDocument) overload specifically, not any of the other overloads on the visitor interface. Together, those two dispatches let a visitor run type-specific logic for every concrete type it encounters, entirely through the type system, without a single instanceof check or manual type inspection anywhere in the code.
Ready to master this question?
Generate a complete walkthrough — background, the full answer in plain language, a working code example explained line by line, a real-world scenario, common mistakes, and how this same question gets asked in different ways.
Sign in to generate a response