例如,我只是想知道如何使用子类来实现父类(super class)。
class Animal {
void poo() {
System.out.println("general poo");
}
}
class Horse extends Animal{
void poo() {
System.out.println("horse poo");
}
}
Animal animal1 = new Horse();
// using this I get the implementation of the Horse class's methods
animal1.poo(); //should return horse poo
尝试向上转型以获得父类(super class)实现,但无济于事
((Animal)animal1).poo() // still returns the horse class's implementation of the method
如何使用animal1对象获取父类(super class)实现?
最佳答案
在 Java 中,不应重写父类(super class)方法,除非新方法旨在完全替代对该方法的所有外部调用。
在 sublcas 实现中,您可以使用例如super.toString() 引用直接父类(super class)方法。
关于java - 如何使用向上转换或其他方法从子类获取父类(super class)的实现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13504039/