0

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:

Animal j = new Cat();

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

2 Answers2

0

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

dev2d
  • 4,245
  • 3
  • 31
  • 54
0

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

Braj
  • 46,415
  • 5
  • 60
  • 76