gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 08:11:56 27 4
gpt4 key购买 nike

如果我有这样的东西:

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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com