Java:与新关键字的接口如何可能? [英] Java: Interface with new keyword how is that possible?
本文介绍了Java:与新关键字的接口如何可能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在从Java库中读取一些源代码,我在这里感到困惑;
I was reading some sourcecode from Java libraries, and I am confused here;
此代码来自jaxb库中的Document.java, ContentVisitor是一个接口在同一个包中,我们如何用一个新关键字创建一个Interface实例?是不是非法?
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代码,你不是在创建一个接口实例。相反,代码定义了一个实现接口的匿名类,并实例化该类。
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.
代码大致相当于:
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();
}
这篇关于Java:与新关键字的接口如何可能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文