gpt4 book ai didi

Java构造函数继承?

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:41:01 24 4
gpt4 key购买 nike

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

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/

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