I was reading some sourcecode from Java libraries, and I am confused here;
This code is from Document.java in jaxb library, and ContentVisitor is an Interfac
It is called anonymous
type/class which implements that interface. Take a look at tutorial - Local and Anonymous Inner Classes.
That declaration actually creates a new anonymous class which implements the ContentVisitor
interface and then its instance for that given scope and is perfectly valid.
You actually have just provided the implementation of this interface in an anonymous way. This is quite common and of course possible. Have a look here for more information.
In the code, you're not creating an instance of the interface. Rather, the code defines an anonymous class that implements the interface, and instantiates that class.
The code is roughly equivalent to:
public final class Document {
private final class AnonymousContentVisitor implements ContentVisitor {
public void onStartDocument() {
throw new IllegalStateException();
}
public void onEndDocument() {
out.endDocument();
}
public void onEndTag() {
out.endTag();
inscopeNamespace.popContext();
activeNamespaces = null;
}
}
private final ContentVisitor visitor = new AnonymousContentVisitor();
}
Since the question is still actual and Java 8 brought in lambda. I must mention it. Lambda comparing with AIC has a couple of advantages.
Do notice where the braces open - you are declaring an inner object (called anonymous class
) that implements ContentVisitor
and all required methods on the spot!