0

Suppose you have an animal inheritance hierarchy. Animal class at the top, Mammal, Fish etc below that, and species (Dog, Cat, Salmon etc below that). Why would someone declare a class such as:

Animal Rover = new Dog();

rather than

Dog Rover = new Dog();

What are the advantages and disadvantages of doing it this way?

VannyJ
  • 67
  • 4
  • 9
  • Read about polymorphism – Andrew Li Jun 03 '17 at 03:18
  • https://stackoverflow.com/questions/12159601/why-do-we-assign-a-parent-reference-to-the-child-object-in-java – qrius Jun 03 '17 at 03:26
  • https://stackoverflow.com/questions/32142128/polymorphism-in-java-why-do-we-set-parent-reference-to-child-object – qrius Jun 03 '17 at 03:28
  • 3
    This has been asked _so many times_ before. But one of the key ideas is that by using a variable of type `Animal` instead of a variable of type `Dog`, you communicate to anyone maintaining your code in the future that you are not using any Dog-specific logic on that variable. Using your code to communicate design intentions is a key part of maintainability. – Dawood ibn Kareem Jun 03 '17 at 03:30

0 Answers0