java - 与基类构造函数相比,什么时候调用 Java 隐式构造函数?

标签 java class inheritance constructor

如果我有这样的东西:

public class SuperClass
{
    SuperClass()
    {
        x = true;
    }
    public boolean x;
}

public class SubClass extends SuperClass
{
    SubClass()
    {
        x = false;
    }
}

我最终创建了一个 SubClass 对象。 x 是真还是假?来自 http://docs.oracle.com/javase/specs/jls/se5.0/html/execution.html#12.5 看起来它会是假的。

最佳答案

来自 Section 12.5 of the Java Language Specification (相关部分加粗):

Just before a reference to the newly created object is returned as the result, the indicated constructor is processed to initialize the new object using the following procedure:

  1. Assign the arguments for the constructor to newly created parameter variables for this constructor invocation.

  2. If this constructor begins with an explicit constructor invocation (§8.8.7.1) of another constructor in the same class (using this), then evaluate the arguments and process that constructor invocation recursively using these same five steps. If that constructor invocation completes abruptly, then this procedure completes abruptly for the same reason; otherwise, continue with step 5.

  3. This constructor does not begin with an explicit constructor invocation of another constructor in the same class (using this). If this constructor is for a class other than Object, then this constructor will begin with an explicit or implicit invocation of a superclass constructor (using super). Evaluate the arguments and process that superclass constructor invocation recursively using these same five steps. If that constructor invocation completes abruptly, then this procedure completes abruptly for the same reason. Otherwise, continue with step 4.

  4. Execute the instance initializers and instance variable initializers for this class, assigning the values of instance variable initializers to the corresponding instance variables, in the left-to-right order in which they appear textually in the source code for the class. If execution of any of these initializers results in an exception, then no further initializers are processed and this procedure completes abruptly with that same exception. Otherwise, continue with step 5.

  5. Execute the rest of the body of this constructor. If that execution completes abruptly, then this procedure completes abruptly for the same reason. Otherwise, this procedure completes normally.

因此父类的构造函数将首先被调用(第 3 步),将 x 设置为 true。在父类(super class)的构造函数被处理并递归地使用相同的步骤完成后,子类的构造函数的主体将其设置为 false(第 5 步)。

关于java - 与基类构造函数相比,什么时候调用 Java 隐式构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27679625/

相关文章:

ios - View Controller 如何展示自己?

javascript - 从回调调用方法时如何从方法获取正确的类上下文

具有继承性的 Java 单例

class - '[Class name]' 不命名 C++ 中的类型

c++ - 为什么我的代码有两个实例而不是一个?

java - Java中如何根据父类(super class)填充子类的字段?

java - 登录http网站java

java - 多次单击按钮后小型 Swing 应用程序崩溃

java - 调用 Java 中另一个循环中创建的变量,以及如何在 do...while 循环中具有多个条件

java - 使用 Java 8 将接口(interface)类型列表转换为另一个类的列表