gpt4 book ai didi

java - 这段 Java 代码中构造函数的顺序是什么?

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:42:07 26 4
gpt4 key购买 nike

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

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

但是我不明白这是怎么发生的?谁能告诉我为什么?

最佳答案

  1. 让我们从Son 的构造函数开始。

    public Son() {
    super(); // implied
    who();
    tell(name);
    }
  2. 父亲的构造函数被调用。

    public Father() {
    who();
    tell(name);
    }
  3. 因为 who()Son 覆盖,Son 的版本将被调用,打印“this is son ".

  4. tell() 也被覆盖但是传入的值是Father.name,打印“this is father”。

  5. 最后,Son 的构造函数中的 who()tell(name) 调用将打印“this是儿子”和“这是儿子”。

关于java - 这段 Java 代码中构造函数的顺序是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9904918/

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