问题
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