【发布时间】:2016-03-07 20:07:53
【问题描述】:
我正在解决一些 Java 难题,偶然发现了这个:
public class Outer {
class Inner1 extends Outer {}
class Inner2 extends Inner1 {}
}
在使用 javac 1.6.0_45 编译此代码时,正如预期的那样,我得到了这个错误:
Outer.java:8: cannot reference this before supertype constructor has been called
class Inner2 extends Inner1 {}
^
这是因为编译器为 Inner2 类生成了具有类似代码的默认构造函数,这解释了上面的错误:
Inner2 () {
this.super();
}
现在很明显,因为在 Java 1.6.0_45、JLS 8.8.7.1 中确实无法做到这一点(我猜到了):
构造函数体中的显式构造函数调用语句可以 不引用在中声明的任何实例变量或实例方法 此类或任何超类,或在任何表达式中使用 this 或 super; 否则,会发生编译时错误。
请参阅(Odd situation for "cannot reference this before supertype constructor has been called" 中的accepted answer)
但如果我尝试用javac 1.7.0_79 编译它 - 没关系!
问题来了 - Java 1.7 中发生了什么变化,这段代码现在是正确的吗?
提前致谢!
【问题讨论】:
-
@EJP 你检查了那个accepted answer,因为那个看起来确实相关
-
@EJP,另外,
this.super()不等同于super()。如果您尝试在非内部非嵌套类中执行此操作,您将收到 [JLS1.6 8.8.7.1] 之前的编译时错误。If S is not an inner class, or if the declaration of S occurs in a static context, no immediately enclosing instance of i with respect to S exists. A compiletime error occurs if the superclass constructor invocation is a qualified superclass constructor invocation.类似于 [JLS1.7 8.8.7.1]。
标签: java java-7 inner-classes java-6