Why assign a subclass object to a superclass reference? [duplicate]

橙三吉。 提交于 2019-12-12 01:43:56

问题


Animal is a superclass

Feline is a subclass of Animal

Cat is a subclass of Feline

Canine is a sublcass of Animal

Dog is a subclass of Canine

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

"(class) is eating"

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

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

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

sorry!


回答1:


Why assign a subclass object to a superclass reference?

  • Polymorphism

  • Mock Object while doing testing

  • Flexibility if you want to replace it with another implementation in future

  • Most likely used in Inheritance and abstract classes




回答2:


by doing the same we achieve runtime polymorphism.

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

now coming toy your question

just a single line answer to that will be

A cat is always an animal

Animal a = new Cat();//ok

All animals are not cat

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

here is a good example to learn and understand this



来源:https://stackoverflow.com/questions/23254070/why-assign-a-subclass-object-to-a-superclass-reference

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!