首先执行哪个,父或子构造函数? [英] Which executed first, The parent or the child constructor?

查看:84
本文介绍了首先执行哪个,父或子构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已将此代码放入编译器中

I've put this code in the compiler

package com.employer.constractor;

public class ConstractorDemo extends A{
    public ConstractorDemo(){
        System.out.print("Demo");
    }
    public static void main(String[] args){
        new ConstractorDemo();
    }
}

class A {
    A(){
        System.out.print("A");
    }
}

它给了 ADemo
为什么?
对于这种情况
,我将不胜感激,并提及编译器将如何处理该问题

And it gave "ADemo" why? I'll appreciate any detailed answer for this case and mention how compiler will deal exactly with that

推荐答案

调用子构造函数时,它将自动将对所有超类的调用链接起来,直到链接到达Object类为止。

When you invoke a child constructor, it automatically chain the calls to it's all super classes until the chain reaches to Object class.

虽然您没有在调用超级类构造函数,但这并不意味着您仅在执行Child类构造函数。有一个有趣的事实,您的超类构造函数(第n个超类,即Object类构造函数)也会在该过程中调用(如代码所示)。您可以观察何时调用任何Child构造函数。当前类有一个到直接父类构造函数的链调用。调用一直持续到Object类构造函数被调用为止,因为可能是大多数Parent类的超类都是这样。

Though you are not invoking Invoking a super class constructor doesn't mean that you are executing only Child class constructor alone. There is a interesting fact that your super class constructors(till n'th super class, which is Object class constructor) also calls in that process(shown in your code). you can observe when you invoke any Child constructor. There is a chain call to the immediate parent class constructor from the current class. And the call continues until the Object class constructor invokes since that the possible most Parent classes super class is.

缩略图规则


  • 如果调用任何特定的超级构造函数(super或super(args)),则
    会调用该特定的超级构造函数。

  • 如果没有调用任何特定的构造函数,则调用默认的super
    构造函数(super())。

这篇关于首先执行哪个,父或子构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆