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