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
  •  | 
  •  

Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top