【发布时间】:2014-04-15 23:02:42
【问题描述】:
在搜索 Java 语言规范以回答 this question 时,我了解到 that
在一个类被初始化之前,它的直接超类必须是 已初始化,但类实现的接口不是 已初始化。 类似地,接口的超接口不是 在接口初始化之前初始化。
出于自己的好奇,我试了一下,果然没有初始化接口InterfaceType。
public class Example {
public static void main(String[] args) throws Exception {
InterfaceType foo = new InterfaceTypeImpl();
foo.method();
}
}
class InterfaceTypeImpl implements InterfaceType {
@Override
public void method() {
System.out.println("implemented method");
}
}
class ClassInitializer {
static {
System.out.println("static initializer");
}
}
interface InterfaceType {
public static final ClassInitializer init = new ClassInitializer();
public void method();
}
这个程序打印
implemented method
但是,如果接口声明了default 方法,那么就会发生初始化。考虑给定的InterfaceType 接口
interface InterfaceType {
public static final ClassInitializer init = new ClassInitializer();
public default void method() {
System.out.println("default method");
}
}
那么上面的程序就会打印出来
static initializer
implemented method
换句话说,接口的static字段被初始化(step 9 in the Detailed Initialization Procedure)并且被初始化类型的static初始化器被执行。这意味着接口已初始化。
我在 JLS 中找不到任何表明应该发生这种情况的内容。不要误会我的意思,我知道这应该发生在实现类没有为该方法提供实现的情况下,但如果它提供了怎么办? Java 语言规范中是否缺少此条件,是我遗漏了什么,还是我解释错误?
【问题讨论】:
-
我的猜测是——这样的接口在初始化顺序方面被认为是抽象类。我将其写为评论,因为我不确定这是否是正确的陈述:)
-
它应该在 JLS 的第 12.4 节中,但似乎没有。我会说它不见了。
-
没关系....大多数情况下,当他们不理解或没有解释时,他们会投反对票:(。这通常发生在 SO 上。
-
我认为Java中的
interface不应该定义任何具体的方法。所以我很惊讶InterfaceType代码已经编译。 -
@MaxZoom Java 8 allows
defaultmethods.
标签: java interface java-8 default-method