4/27 Dear Java gurus, say I have the following code, where Visitor()
has a method called "visit(Node n)...". I see the following code.
Does it mean I'm temporarily over-writing the visit method?
root.accept(new Visitor() {
public void visit(Node n) {
//Do stuff with n
}
});
\_ for a lot more on the above code, see Erich Gamma's book
"Design Patterns" (introduction and visitor pattern)
\_ It's an anonymous class and yup you've got it. Even more
useful is the fact that as long as you have final variables
in the code that calls visit, you can use those variables
in the redefinition of visit.
final Long x;
root.accept(new Visitor() {
public void visit(Node n, Long y) {
super.visit(n, x+y);
}
});
Is valid. (I may have a few details wrong, but that's the basic
idea. See documentation for anonymous classes if you want to
know more.)
\_ To slightly correct the above, it's an anonymous *inner*
class, which is the Java version of a closure-like-thing
(lamdas if you know LISP, Blocks if you do Smalltalk).
If you aren't familiar with them, you should write a few little
programs to explore them -- they can be quite useful.
\_ Did you actually try compiling the above code or the code
below it? It doesn't seem to work.
\_ No, no I didn't. I just gave the concept. Note where
I said I may have a few details wrong. Here, because you
are obviously unable to fill in the blanks yourself...
public class Foo {
public Foo() {
}
public void a(Long a) {
System.out.println("a("+a+")");
}
public void doA(Long a) {
final Long b = new Long(11);
new Foo() {
public void a(Long a) {
super.a(new Long(b.longValue()+a.longValue()));
}
}.a(a);
}
public static void main(String[] args) {
new Foo().doA(new Long(5));
}
} |