java - 如何使用向上转换或其他方法从子类获取父类(super class)的实现?

标签 java downcast upcasting

例如,我只是想知道如何使用子类来实现父类(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/

相关文章:

java - 从父类(super class) : Node to SpecialNode in a linked list 向下转型

arrays - SWIFT - 将数组向下转换为字符串

c++ - 为什么 C 样式转换允许您转换为私有(private)基类?

java - 子类的对象不能调用自己的方法

java - 如何将 JsonNode 实例转换为实际的 pojo

java - 使用 Maven 只重建必要的 jar

Java:转换 ParentClass 和 ChildClass(向下转型运行时错误)

c++ - 类的转换(向上转换)

java - 走出while循环

java - 如何在没有变量的情况下从枚举中获取值