Hisham Muneer Hisham Muneer - 1 month ago 6
Java Question

how to call the overridden method of superclass

Maybe this could be very simple but I am confused about my little example.

public class Animal {
public void eat() {
System.out.println("Animal Eats");
}

public void shit() {
System.out.println("Animal Shits");
}
}





public class Cat extends Animal {
@Override
public void eat() {
System.out.println("Cat Eats");
}

@Override
public void shit() {
System.out.println("Cat Shits");
}

public static void main(String[] args) {
Cat myCat = new Cat();
myCat.eat();
myCat.shit();

Animal myAnimal = myCat;
myAnimal.eat();
myAnimal.shit();

}
}





Output that I am getting:

Cat Eats
Cat Shits
Cat Eats
Cat Shits


How can I call the eat and shit method of Animal class with myAnimal object in the code.
Thanks.

So that I can get this output:

Cat Eats
Cat Shits
Animal Eats
Animal Shits

Answer

You cannot do what you want. The way polymorphism works is by doing what you are seeing.

Basically a cat always knows it is a cat and will always behave like a cat regardless of if you treat is as a Cat, Felis, Felinae, Felidae, Feliformia, Carnivora, Theria, Mammalia, Vertebrata, Chordata, Eumetazoa, Animalia, Animal, Object, or anything else :-)