0

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?

chip
  • 3,039
  • 5
  • 35
  • 59

2 Answers2

7

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.

Patricia Shanahan
  • 25,849
  • 4
  • 38
  • 75
  • 2
    That. `Horse.poo` should be fully compliant with the contract/specification of `Animal.poo`; if it is not true you have a trouble with your design. – SJuan76 Nov 22 '12 at 00:15
  • @Patricia. Thanks for the answer. I guess the best way to do this is to created a method that would do the super.method(). :D – chip Nov 22 '12 at 09:41
  • You need to decide which is the normal way of doing poo in your new subclass. That should override the superclass method. You can either add a new method to do the new thing, or add a new method to do the superclass version. However, I suggest carefully reviewing your design - hitting this problem is often a symptom of confusion about what methods are meant to do. – Patricia Shanahan Nov 22 '12 at 17:12
1

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

AlexWien
  • 28,470
  • 6
  • 53
  • 83
  • yeah, i agree to that. and so are the test questions that i encounter when i apply for jobs. – chip Nov 22 '12 at 09:38