Visitor Pattern Implementation in Java
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Visitor Pattern runs in O(n) time and O(n) space, in Java as in every other language.
- ✓Java is where this pattern comes from and the JDK ships real examples: javax.lang.model.element.ElementVisitor and javax.lang.model.type.TypeVisitor, used by annotation processors, with abstract base classes providing defaults.
- ✓For new code, use a sealed interface and a switch with record patterns; the compiler then proves every node is handled and adding a node breaks the build at every operation, which is exactly the guarantee the classical visitor lacks.
- ✓The Java trap: The classical visitor gives NO compile-time guarantee that a visitor handles every node: adding a node type compiles fine, and unless each visitor is abstract with no default, the new node falls into a default that does nothing.
- ✓The accept bounce doubles the number of virtual calls per node, and both call sites go megamorphic once several node types flow through them, so the JIT stops inlining and a large traversal pays for it.
What Visitor Pattern actually is
Visitor Pattern in Java: what you actually reach for
Java implementation
sealed interface Node permits Num, Add, Mul {}
record Num(double value) implements Node {}
record Add(Node left, Node right) implements Node {}
record Mul(Node left, Node right) implements Node {}
class Eval {
// Java 21: exhaustive over the sealed hierarchy. NO accept(), no default.
static double evaluate(Node n) {
return switch (n) {
case Num(double v) -> v;
case Add(Node l, Node r) -> evaluate(l) + evaluate(r);
case Mul(Node l, Node r) -> evaluate(l) * evaluate(r);
};
}
}
// The CLASSICAL form, and why accept() has to exist:
interface Visitor<R> { R visitNum(Num n); R visitAdd(Add a); }
interface Visitable { <R> R accept(Visitor<R> v); }
// Overloads resolve on the STATIC type at COMPILE time, so this would always
// pick the Node overload and never dispatch, the accept() bounce fixes it:
// void visit(Node n) {} void visit(Num n) {}
// Node x = new Num(1); visit(x); // calls visit(Node), NOT visit(Num)Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Java-specific trap
Performance in Java, beyond the O(n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Java type or library should I use for Visitor Pattern?
Java is where this pattern comes from and the JDK ships real examples: javax.lang.model.element.ElementVisitor and javax.lang.model.type.TypeVisitor, used by annotation processors, with abstract base classes providing defaults. The classical form is an accept method on each node taking a Visitor and calling back the matching visit overload, which is genuine double dispatch built from two single dispatches. Since Java 21, pattern matching for switch over a sealed hierarchy, with record patterns for destructuring, does the same job with compiler-checked exhaustiveness and no accept methods.
What is the most common Java mistake when implementing Visitor Pattern?
The classical visitor gives NO compile-time guarantee that a visitor handles every node: adding a node type compiles fine, and unless each visitor is abstract with no default, the new node falls into a default that does nothing. That is the expression problem, and the whole reason the pattern is hard to maintain. Overloading is a separate trap: visit methods distinguished only by parameter type are resolved at COMPILE time on the static type, so calling visitor.visit(node) with node typed as the interface always picks the interface overload and never dispatches; the accept bounce exists precisely because of that, and forgetting it produces a visitor that compiles and always calls the wrong method.
How does Visitor Pattern actually perform in Java?
The accept bounce doubles the number of virtual calls per node, and both call sites go megamorphic once several node types flow through them, so the JIT stops inlining and a large traversal pays for it. A switch with type patterns compiles to a sequence of type checks or, since Java 21, an invokedynamic-backed type switch that can be more efficient than a chain, and it avoids the second dispatch entirely, so the modern form is usually faster as well as safer. Time complexity is O(n) and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialBefore paying full price for a tool, check the student deals on AI and developer tools listed on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.