gpt4 book ai didi

java - 为什么父类(super class)调用子类的重写方法?

转载 作者:行者123 更新时间:2023-11-30 07:14:51 25 4
gpt4 key购买 nike

我有两个类,Parent(父类(super class))和 Child(子类)。

public class Parent(){

public void hello(){
System.out.println("HelloParent");
bye();
}

public void bye(){
System.out.println("ByeParent");
}
}

public class Child extends Parent(){

@Override
public void hello(){
super.hello();
}

@Override
public void bye(){
System.out.println("ByeChild");
}
}

如果我创建一个 Child 实例并调用它的 hello() 方法,它会调用 Childhello 方法,而不是 Parenthello 方法。

Child c = new Child();
c.hello();

输出:

"HelloParent"
"ByeChild"

但为什么不是“ByeParent”呢?

为什么它不调用父类(super class)的方法?

最佳答案

无论代码在哪里,任何实例方法调用都将发生在实例所属的对象上。所以在执行这段代码时:

 public void hello(){
System.out.println("HelloParent");
bye();
}

bye 方法将在调用对象上调用,即 Child,因此调用 Child 方法。

关于java - 为什么父类(super class)调用子类的重写方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18299945/

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