如何调用超类的重写方法? [英] How to call the overridden method of a superclass?

查看:98
本文介绍了如何调用超类的重写方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在代码中使用 myAnimal 实例调用 Animal 类的吃喝方法?

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();
    }
}

我得到的输出:

Cat Eats
Cat Drinks
Cat Eats
Cat Drinks

这是我的预期输出:

Cat Eats
Cat Drinks
Animal Eats
Animal Drinks


推荐答案

你无法做你想做的事。多态性的工作方式是做你所看到的。

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

基本上猫总是知道它是一只猫而且总是表现得像一只猫,无论你是否像对待一样猫,猫科动物,猫科动物,猫科动物,猫科动物,食肉目,咏叹调,哺乳动物,脊椎动物,脊索动物,Eumetazoa,动物,动物,物体或其他任何东西: - )

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

这篇关于如何调用超类的重写方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆