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

标签 java oop inheritance constructor

我知道,在继承的情况下,如果父类(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/

相关文章:

java - 无法调用网络服务

javafx - 当选择一个时 TableView 中的复选框,行中的其他复选框被禁用

java - 安卓 : Unable to Access Function From Other Class (Service)

Java OOP 问题 - 与接口(interface)/抽象类相关

c++ - gcc4.9.2的std::vector的libstdc++实现继承自_Vector_base(非虚拟析构函数)。为什么这样可以?

c# - 继承与类型转换

java - 使用分割方法

mongodb - 域对象中的关系引用 - 是否包含 Id?

c++ - 只有当 len < 3 时,我才会收到堆损坏错误。怎么会?

c# - :base() in a constructor的使用