如何使用upcasting或其他方法从子类实现超类?

nic*_* m. 0 java downcast upcasting

我只是想知道如何使用子类来实现超类,例如.

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
Run Code Online (Sandbox Code Playgroud)

试图升级它以获得超级类实现,但无济于事

((Animal)animal1).poo() // still returns the horse class's implementation of the method
Run Code Online (Sandbox Code Playgroud)

如何使用animal1对象获取超类实现?

Pat*_*han 7

在Java中,除非新方法旨在完全替换方法的所有外部调用,否则不应覆盖超类方法.

在sublcass实现中,您可以使用例如super.toString()来引用直接超类方法.

  • 那.`Horse.poo`应完全符合`Animal.poo`的合同/规范; 如果不是这样,你的设计有问题. (2认同)