java - JDK 1.7 vs JDK 1.6 内部类继承区别

标签 java java-7 inner-classes java-6

我正在解决一些 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 if S is not a member of a lexically enclosing class, or of a superclass or superinterface thereof. Let O be the innermost lexically enclosing class of which S is a member, 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 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/

相关文章:

macos - Java 应用程序无法在 Mac 上找到 JDK 1.7(使用 install4j 创建的安装程序)

java - 写入包含非英文字符的文件名时不正确的 zip 条目,即使使用 Java 7

java - 如何获取公共(public)内部枚举的所有元素的列表?

Swift 继承嵌套/内部枚举问题

java - JUnit 规则临时文件夹

java - TimeHandler 中抛出 IndexOutOf range 异常

java - 使用 Java EE API 替换已弃用的 JPMS 模块

Maven 使用 JDK6 构建成功,但使用 JDK7 失败

java - 我无法从 AbstractAction 内部类中声明的 actionPerformed 设置不可见的 JFrame,如何解决?

java - Java中的子类和父类(super class)