gpt4 book ai didi

Java向下转型对象调用子方法

转载 作者:行者123 更新时间:2023-11-30 02:35:29 25 4
gpt4 key购买 nike

打印输出是:水果 苹果 金的 金色

我想知道为什么对象 c.make()调用 class Golden 中的方法而不是class Apple因为我认为c是Apple类的对象,我的错误在哪里?感谢您的考虑。

public class Fruit {
public Fruit(){
System.out.println("Fruit");
}
public void make(){
System.out.println("Fruit");
}

}
class Apple extends Fruit{
public Apple(){
System.out.println("Apple");
}
public void make(){
System.out.println("Apple");
}
}
class Golden extends Apple{
public Golden(){
System.out.println("Golden");
}
public void make(){
System.out.println("Golden");
}
}
public class tet {

public static void main(String[] args){
Fruit b = new Golden();//Fruit Apple Golden
Apple c = (Apple)b;
c.make();
}



}

最佳答案

不,cb 相同。事实上,它们指向同一个完全相同的对象,该对象的类型为Golden。您只需选择通过 Apple 引用“查看”对象,但实际类型不会改变。

关于Java向下转型对象调用子方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43232005/

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