有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

继承在Java中,超级构造函数调用是否可能实际调用调用类中的构造函数?

Super constructor invocation definition

[Primary.] [NonWildTypeArguments] super ( ArgumentListopt ) ;

超级构造函数调用的前缀可以是Primary表达式。示例(摘自JLS):

class Outer {
    class Inner{ }
}

class ChildOfInner extends Outer.Inner {
    ChildOfInner() {
        (new Outer()).super(); // (new Outer()) is the Primary
    }
}

是否存在使对super()的调用成为调用类的构造函数调用的Primary表达式?还是Java阻止了


共 (2) 个答案

  1. # 1 楼答案

    据我所知,Java中的构造函数不是虚拟的(基类不能从派生类调用任何构造函数)。实际上,您可以在构造函数中调用方法,这些方法将像在最终确定的对象上一样被调用。但这可能会引入一些微妙的错误(因为从基类构造函数调用该方法时,不会对派生类成员执行初始化)

    查看以下内容,了解更完整的讨论:

    http://www.codeguru.com/java/tij/tij0082.shtml

  2. # 2 楼答案

    Does a Primary expression exist that makes the call to super() the invocation of a constructor of the calling class?

    不。没有办法将super()调用转移到与使用this()等效的位置。Primary的唯一原因是在超类是非静态内部类时提供实例化的外部上下文

    主表达式不是选择构造函数或类,而是传递一些构造函数所需的上下文信息(即非静态内部类所需的外部实例)

    编辑:

    OP需要一个来源。我没有——我的回答完全基于我对规范的阅读,我认为这一点非常清楚:

    ... the keyword super ... used to invoke a constructor of the direct superclass.

    If the superclass constructor invocation is qualified, then the Primary expression p immediately preceding ".super" is ... the immediately enclosing [outer] instance ... it is a compile-time error if the type of p is not O [outer class] or a subclass of O.

    如果super上有限定表达式,则它只能用于返回超类的封闭类的实例(或超类的封闭类的子类的实例)。限定表达式与响应super()调用哪个类的构造函数没有关系,也就是说,限定表达式不能返回任何值来更改调用哪个类的构造函数,因为super()-super()总是调用直接超类的构造函数