How to call the overridden method of a superclass?

Hisham Muneer picture Hisham Muneer · Mar 27, 2013 · Viewed 79k times · Source

How can I call the eat and drink method of the Animal class with the myAnimal instance in the code?

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

    public void drink() {
        System.out.println("Animal Drinks");
    }
}

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

    @Override
    public void drink() {
        System.out.println("Cat Drinks");
    }

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

        Animal myAnimal = myCat;        
        myAnimal.eat();
        myAnimal.drink();
    }
}

Output that I am getting:

Cat Eats
Cat Drinks
Cat Eats
Cat Drinks

This is my expected output:

Cat Eats
Cat Drinks
Animal Eats
Animal Drinks

Answer

TofuBeer picture TofuBeer · Mar 27, 2013

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 :-)