Java构造函数继承?

标签 java inheritance constructor

我一直以为构造函数不是继承的,但是看看这段代码:

class Parent {
    Parent() {
        System.out.println("S1");
    }
}

class Child extends Parent {
    Child() {
        System.out.println("S2");
    }
}

public class Test5 {
    public static void main(String[] args) {
        Child child = new Child();
    }
}

//RESULT:
//S1
//S2

说明Child继承了构造函数。为什么结果上有S1?是否有可能创建 2 个不带参数的构造函数并且在结果上只有子构造函数而没有基本构造函数(仅 S2)?

最佳答案

无论您在这里看到什么,都称为构造函数链。现在什么是构造函数链接:

Constructor chaining occurs through the use of inheritance. A subclass constructor method's first task is to call its superclass' constructor method. This ensures that the creation of the subclass object starts with the initialization of the classes above it in the inheritance chain.

There could be any number of classes in an inheritance chain. Every constructor method will call up the chain until the class at the top has been reached and initialized. Then each subsequent class below is initialized as the chain winds back down to the original subclass. This process is called constructor chaining.(Source)

这就是您的程序中发生的事情。当你编译你的程序时,你的 Childjavac 编译成这样:

class Child extends Parent 
{ 
  Child()
  {
    super();//automatically inserted here in .class file of Child
    System.out.println("S2");
  }
}

并且您的父类转换为以下内容:

Parent() 
{
    super();//Constructor of Object class
    System.out.println("S1");
}

这就是为什么您的输出显示为:

S1 //output from constructor of super class Parent
S2 //output from constructor of child Class Child

关于Java构造函数继承?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15721764/

相关文章:

java - 如何创建 DRYer 构造函数

java - 模拟 ReactiveSecurityContextHolder

java - 在 Windows 7 上,Java JVM 如何设置 "user.home"系统属性?

c++ - 如何使用匿名模板参数强制模板参数类从 super 派生

c++ - 实例化从 Base 私有(private)或 protected 继承的派生类

c++ - 从父类(super class)调用子类中的虚函数

c++ - Objective C 类方法 == C++ 构造函数?

c# - 调用泛型类构造函数的困境

java - 运行 spark 作业时 cpu 使用率低

java - 从父引用调用子类的方法