打印输出是:水果 苹果 金 金的Java垂头丧气对象调用子方法
我想知道为什么对象c.make()
在class Golden
调用的方法,而不是class Apple
。因为我认为C是对象苹果课,我的错误在哪里?感谢您的考虑。
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();
}
}
因为即使你把它转换为'Apple',它仍然是类型的对象'Golden',而且由于'make'方法被重写了'Golden'类中的一个被调用。 – BackSlash
(苹果)b出现时堆栈和堆中会发生什么?什么都没有发生,包括b指向堆的方向? –
要非常简单的**第1 **在堆'与您使用'new'运营商创造object'那类。 **第2 **与您使用'new'和所有的'类和interfaces'在该类的更高层次的类的参考只允许指创建的对象。 *注意*引用猫的狗是无效的,并提及一只动物的狗不会剥夺吠叫的能力,其作为它的狗**。 :) –