gpt4 book ai didi

java - 链接到子类中的另一个构造函数

转载 作者:行者123 更新时间:2023-11-30 03:01:05 25 4
gpt4 key购买 nike

我知道,在继承的情况下,如果父类(super class)中的默认构造函数丢失,子类构造函数应该显式调用父类(super class)构造函数

但是当链接到子类中的另一个构造函数时,为什么我们不必调用父类(super class)构造函数呢?因为下面的代码没有给出编译错误

父类(super class):

public class Top {
public Top(String n) {
// TODO Auto-generated constructor stub
}

子类:

public class sub extends Top {

public sub(int x){
super("");
}
public sub(String x) {
this(5);
}
}

最佳答案

因为“链式”构造函数将调用父类(super class)构造函数本身。否则,您将调用父类(super class)构造函数两次(因此父类构造函数的效果将执行两次,这可能会导致行为不一致,例如调用实例初始值设定项两次)。更正式地说,构造函数调用的顺序在 this section of the Java Language Specification 中进行了解释。 :

  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.

...

请注意,步骤 2 是递归的,并且适用于调用子类中其他构造函数的构造函数。步骤3适用于调用父类构造函数的构造函数。

关于java - 链接到子类中的另一个构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35949937/

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