gpt4 book ai didi

java - JAVA中是否有在父类(super class)的构造函数之前执行子类的构造函数?

转载 作者:行者123 更新时间:2023-11-30 02:24:31 25 4
gpt4 key购买 nike

class Super
{
Super()
{
System.out.println("This is Super Constructor");
}
}
class Sub extends Super
{
Sub()
{
//super() is automatically added by the compiler here!
System.out.println("This is Sub Constructor");
//super(); I can't define it here coz it needs to be the first statement!
}
}
class Test
{
public static void main(String...args)
{
Sub s2=new Sub();
}
}

输出:
这是 super 构造函数
这是子构造函数

无论如何都要这样做吗?
或者你不能在Super()之前访问Sub()?
我知道父类(super class)或继承类首先被初始化,然后是子类,这样做只是为了学习目的!

最佳答案

在构造函数中,编译器始终会添加对 super() 的调用如果您不是自己调用此电话,则为您提供。

如果您使用反编译器查看,您的 Sub 构造函数将如下所示:

Sub()
{
super();
System.out.println("This is Sub Constructor");
}

所以不,这是不可能的。

关于java - JAVA中是否有在父类(super class)的构造函数之前执行子类的构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45988216/

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