gpt4 book ai didi

java - 编译器在 java 子类的有参构造函数中调用无参数 super()

转载 作者:行者123 更新时间:2023-12-01 14:21:32 25 4
gpt4 key购买 nike

我们开始:

public class Parent {

public Parent(String name) {
this.name = name;
}

public String name = null;

}

public class Child extends Parent {

public Child(String name) {
super(name); // If I comment this : Implicit super constructor Parent() is undefined. Must explicitly invoke another constructor
}

}

据说“如果您不自己调用 super 构造函数,编译器将为您插入对 super() 的无参数调用,作为构造函数中的第一个语句。”

  • 对于带参数的构造函数来说也是如此吗?
  • 编译器一定不能使用与子构造函数相同的签名来调用带参数的 super 构造函数吗?
  • 为什么要这样设计?

最佳答案

Is this true for the argument-ed constructors as well?

是的。

Mustn't the compiler call the argument-ed super constructor with the same signature of the child constructor?

没有。如果您想要调用不同的基类构造函数,则必须自己调用它,并根据需要传递参数。

Why it has been designed like this?

因为您提出的替代方案(自动转发所有参数)一般来说不是很有用。

关于java - 编译器在 java 子类的有参构造函数中调用无参数 super(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17509074/

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