为什么将子类对象分配给超类引用? [英] Why assign a subclass object to a superclass reference?

查看:47
本文介绍了为什么将子类对象分配给超类引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

动物是超类

猫是动物的一个子类

猫是猫的一个子类

犬是动物的子类

Dog 是 Canine 的一个子类

Dog is a subclass of Canine

所有的类都有自己的eat()方法输出:

All of the classes have their own eat() method that outputs:

(班级)正在吃饭"

我已经尝试过创建一个 Animals 数组,遍历它们,然后调用eat() 方法,该方法为每个给定的动物输出正确的输出.

I've already tried creating an array of Animals, looping through them, and calling the eat() method, which outputs the proper output for each given animal.

我的问题是,这样做有什么好处:

My question is, what does one gain by doing this:

Cat j = new Animal();

Cat j = new Cat() 不会对带有 Animal 类型的方法做任何您需要做的事情,因为它已经通过继承成为一种动物?

wouldn't Cat j = new Cat() do anything you need do regarding methods with Animal types, since it's already an animal through inheritance?

对不起,我的意思是反过来——声明有什么好处:动物 j = new Cat();

I'm sorry, I meant it the other way around--what does one gain by declaring: Animal j = new Cat();

对不起!

推荐答案

通过这样做,我们实现了运行时多态性.

by doing the same we achieve runtime polymorphism.

根据对象的类型,将调用重写的方法

based on the type of object the overridden method will be called

现在来玩你的问题

只需一行答案

猫永远是动物

Animal a = new Cat();//ok

不是所有的动物都是猫

Cat c = new Animal();//not ok

这里是学习和理解这一点的好例子

here is a good example to learn and understand this

这篇关于为什么将子类对象分配给超类引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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