我正在解决一些 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 中这样做(我猜):
An explicit constructor invocation statement in a constructor body may not refer to any instance variables or instance methods declared in this class or any superclass, or use this or super in any expression; otherwise, a compile-time error occurs.
参见(accepted answer 中的 Odd situation for "cannot reference this before supertype constructor has been called")
但如果我尝试用 javac 1.7.0_79
编译它 - 没问题!
问题来了 - Java 1.7 中发生了什么变化,这段代码现在是正确的?
提前致谢!
最佳答案
看起来有人讨论了与错误 JDK-6708938: Synthetic super-constructor call should never use 'this' as a qualifier 相同的问题在 Java 错误跟踪器上。
此外,我认为您最好看看上一期的其他相关问题,例如 JDK-4903103: Can't compile subclasses of inner classes .
注意这两个错误的修复版本。
结果见 Maintenance Review of JSR 901 (Java Language Specification) for Java SE 7 .
来自 The Java Language Specification Third Edition
Otherwise,
S
is an inner member class (§8.5). It is a compile-time error ifS
is not a member of a lexically enclosing class, or of a superclass or superinterface thereof. LetO
be the innermost lexically enclosing class of whichS
is a member, and let n be an integer such thatO
is the n th lexically enclosing class ofC
. The immediately enclosing instance ofi
with respect toS
is the n th lexically enclosing instance of this.
来自 Java SE 7 的 JSR 901(Java 语言规范)的维护审查(完整版,第 242 页,蓝色文本)或 The Java Language Specification, Java SE 7 Edition 中的相同内容(就在第 8.8.8 节之前)
Otherwise, S is an inner member class (§8.5).
Let O be the innermost lexically enclosing class of S, and let n be an integer such that O is the n'th lexically enclosing class of C.
The immediately enclosing instance of i with respect to S is the n'th lexically enclosing instance of this.
所以你可以看到编译时错误的部分已经消失了。
关于java - JDK 1.7 vs JDK 1.6 内部类继承区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35853023/