JAVA 中有没有在 Super Class 的构造函数之前执行 Sub Class 的构造函数?
Is there anyway in JAVA to execute Sub Class's Constructor before the Super Class's Constructor?
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() 之前访问 Sub()?
我知道 Super Class 或 Inherited Classes 首先被初始化,然后是 sub 类,这样做只是为了学习目的!
在构造函数中,编译器总是会添加对 super()
的调用
如果您自己没有提供此电话,则为您提供。
如果您使用反编译器查看,您的 Sub 构造函数将如下所示:
Sub()
{
super();
System.out.println("This is Sub Constructor");
}
所以不,这是不可能的。
它总是会先调用基础 class 构造函数(父),然后再调用初始化 class(子)。在您的情况下 super()
将首先执行。
读得好:Which executed first, The parent or the child constructor?
正如其他答案所说不可能。不确定您为什么要尝试这样做,但最好重新考虑您的实现,因为您总是希望确保首先初始化继承字段,因为子 class 实现可能依赖于它。
如前所述,总是调用超级构造函数。也许你应该重写你的问题并解释,为什么你需要那个。
这是一个简单的答案。
继承的概念是关于IS-A关系的。
所以从技术上讲,Dog class 是 Animal Class 的 child。 . .
创建 object 后,狗 class 首先是 ANIMAL,然后 class 化为 DOG
...希望这能澄清事情。 .所以不可能按照你要求的方式去做
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() 之前访问 Sub()?
我知道 Super Class 或 Inherited Classes 首先被初始化,然后是 sub 类,这样做只是为了学习目的!
在构造函数中,编译器总是会添加对 super()
的调用
如果您自己没有提供此电话,则为您提供。
如果您使用反编译器查看,您的 Sub 构造函数将如下所示:
Sub()
{
super();
System.out.println("This is Sub Constructor");
}
所以不,这是不可能的。
它总是会先调用基础 class 构造函数(父),然后再调用初始化 class(子)。在您的情况下 super()
将首先执行。
读得好:Which executed first, The parent or the child constructor?
正如其他答案所说不可能。不确定您为什么要尝试这样做,但最好重新考虑您的实现,因为您总是希望确保首先初始化继承字段,因为子 class 实现可能依赖于它。
如前所述,总是调用超级构造函数。也许你应该重写你的问题并解释,为什么你需要那个。
这是一个简单的答案。 继承的概念是关于IS-A关系的。 所以从技术上讲,Dog class 是 Animal Class 的 child。 . . 创建 object 后,狗 class 首先是 ANIMAL,然后 class 化为 DOG
...希望这能澄清事情。 .所以不可能按照你要求的方式去做