Question:
I am struggling with basic OOP. I feel like I’m under utilizing the dog and cat classes below and don’t know how to call them from the driver so I can avoid rewriting identical code to handle each subclass I may want to print a list of.This code loops an options menu and a user can either print a doglist, print a monkeyList, or quit. It is a scaled down version of a larger code which has more options. I have left the monkey and dog intake methods to show list contents, but instantiating new dogs or monkeys is not functional in this example.
My main concern is with the printAnimals() method. Yes, it works as is, but what if in the future I want to add bears, and horses, and cats…it will be necessary to keep writing individual loops for each new class I want to print a list of. There has to be a way to apply a single loop that handles all the classes, right?
Answer:
Add atoString()
method to each of your animal classes, e.g:Monkey
.Change
printAnimals
so that you pass it specific List<RescueAnimal>
:printAnimals()
can print any sort of animal.And your
case
above becomes:If you have better answer, please add a comment about this, thank you!