gpt4 book ai didi

Java重写困惑

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:47:24 25 4
gpt4 key购买 nike

我是 java 的新手,现在我有一个关于方法覆盖的问题:

public class maintest {
public static void main(String[] args) {
new Zi();
}
}

public class Fu {

public Fu() {
show();
}
public void show() {
System.out.println("This is from Fu show");
}
}

public class Zi extends Fu {
public Zi() {
show();
super.show();
}

public void show() {
System.out.println("This is from zi show");
}
}

当我运行这个程序时,输出是:

This is from zi show
This is from zi show
This is from Fu show

谁能给我一些关于为什么第一行输出是

的简单易懂的解释
This is from zi show

而不是

This is from Fu show

换个说法,为什么父类(super class)中的show方法被隐藏了?

最佳答案

在你的构造函数中你这样做,

public Zi() {
super(); // <-- you didn't have this, so the compiler added it.
// your Fu class then calls Zi's show.
// Why? Because Zi has a method named show that override Fu's
// show method. So the Fu constructor (when it calls show()) gets the
// show implementation in Zi.
show(); // <-- first explicit show call (but the second "This is from zi show")
super.show(); // <-- then call the Fu.show()
}

关于Java重写困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22369373/

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