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 Interface in same package, how can we create an instance of Interface with a new keyword? isn't that illegal?
public final class Document {
.
.
private final ContentVisitor visitor = new ContentVisitor() {
public void onStartDocument() {
throw new IllegalStateException();
}
public void onEndDocument() {
out.endDocument();
}
public void onEndTag() {
out.endTag();
inscopeNamespace.popContext();
activeNamespaces = null;
}
}
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();
}
thanks does this syntax(anonymous class) only saves us from writing some extra code or it has other advantages or uses too?
It saves having to write extra code and coming up with a name. The name is more likely to be
Document$1
in the above example.@DesignCode: It's mainly syntactic sugar, but does have unique selling points as well. For example, if such a class is defined inside a function, it can access
final
variables defined inside the function.