在我的代码中有两个类,子类扩展了超类。在子类中我覆盖了超类方法。在创建对象时,我创建了对子类对象的超类引用,它工作正常。但是我再次将超类引用转换为完整的超类对象,但它调用子类方法而不是超类方法。我的假设输出是错误的。这是我的代码
public class OverRiding {
public static void main(String[] args) {
// TODO Auto-generated method stub
//Super class reference to sub class Object
Dog dog = new Animal();
dog.eat();
dog.bow();
//Completely converted into pure Dog class Object
Dog d = (Dog) dog;
d.eat();
d.bow();
}
}
狗类
class Dog {
public void eat() {
System.out.println("Dog eat Biscuits");
}
public void bow() {
System.out.println("Dog bow");
}
}
动物类
class Animal extends Dog {
public void eat() {
System.out.println("Animal eat Food");
}
}
我的输出是
Animal eat Food
Dog bow
Animal eat Food
Dog bow