本Java代码中构造函数的顺序是什么? [英] What is the order of the Constructors in this Java Code?

查看:111
本文介绍了本Java代码中构造函数的顺序是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是代码,我定义了两个名为Father和Son的类,并在main函数中创建它们:

Here is the code, I defined two class named Father and Son, and create them in the main function:

public class Test {
    public static void main(String[] args) {
        Father father = new Son();
    }
}

class Father {
    private String name = "father";
    public Father() {
        who();
        tell(name);
    }
    public void who() {
        System.out.println("this is father");
    }
    public void tell(String name) {
        System.out.println("this is " + name);
    }
}

class Son extends Father {
    private String name = "son";
    public Son() {
        who();
        tell(name);
    }
    public void who() {
        System.out.println("this is son");
    }
    public void tell(String name) {
        System.out.println("this is " + name);
    }
}

我得到的输出如下:

this is son
this is father
this is son
this is son

但我无法理解这是怎么发生的?任何人都可以告诉我为什么?

But I can not understand how this happened? Anyone can tell me why?

推荐答案


  1. 让我们从<$ c的构造函数开始$ c>儿子。

public Son() {
    super(); // implied
    who();
    tell(name);
}


  • 调用父的构造函数。

  • Father's constructor is called.

    public Father() {
        who();
        tell(name);
    }
    


  • 因为 who() Son 覆盖,将调用 Son 的版本,打印this is son 。

  • Because who() is overridden by Son, the Son's version will be called, printing "this is son".

    tell()也被覆盖,但传入的值是父。名,打印这是父亲。

    tell() is also overridden but the value passed in is Father.name, printing "this is father".

    最后, who()告诉(姓名)调用儿子的构造函数将被打印这是儿子和这是儿子。

    Finally, the who() and tell(name) calls inside Son's constructor will be made printing "this is son" and "this is son" respectively.

    这篇关于本Java代码中构造函数的顺序是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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