how to get the implementation of a superclass from a subclass using upcasting or by other methods?

StackOverflow https://stackoverflow.com/questions/13504039

  •  01-12-2021
  •  | 
  •  

i just wanted to know how to get the implementation of a superclass using a subclass, for example.

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

tried to upcast it to get the super class implementation but to no avail

((Animal)animal1).poo() // still returns the horse class's implementation of the method

How do I get the superclass implementation using the animal1 object?

有帮助吗?

解决方案

In Java, you should not override a superclass method unless the new method is intended to be a total replacement for all external calls to the method.

Within the sublcass implementation, you can use e.g. super.toString() to reference the immediate superclass method.

其他提示

Beside it is not possible, it does not make sense, try to redsign your class.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top