Computer Science Canada Noah's Boat |
Author: | keyboardwalker [ Mon Jun 23, 2014 9:37 pm ] |
Post subject: | Noah's Boat |
Noah has a boat with of every single species of animal on it that have >=2 animals of each species. It is dinner time on the boat and Noah must then call a unique "eat" method for each of the animals to feed them. All of different types of animals are a subclass of Animal. So the question is, what kind of data structure would allow for all of these semi-unique objects to preform the "eat" method easily. You could of course make an array for each of the different 'species' (classes) and then run through all of the arrays and objects and call the "eat" method but that would be a sizable amount of code. Is there any way to do this more elegantly? To put it in a slightly more technical way There are many different classes and each have a varying number of instances (objects). The said classes are all sub classes of the same class. All of the objects have a common method that must be called. The method is slightly different but has the same method name (polymorphism). Is there a data structure that allows for this en masse method-calling to be easily done? |
Author: | Insectoid [ Mon Jun 23, 2014 9:41 pm ] |
Post subject: | RE:Noah\'s Boat |
Look up virtual methods and interfaces. |
Author: | Raknarg [ Mon Jun 23, 2014 9:47 pm ] | ||
Post subject: | RE:Noah\'s Boat | ||
If you need to have each type of animal separated, you could use an array list of arraylists. Otherwise, use a single arraylist. Here's an example using a single arrayList:
Personally I would make Animal an abstract class instead and make eat an abstract method, or use an interface. |
Author: | keyboardwalker [ Wed Jun 25, 2014 9:03 am ] |
Post subject: | RE:Noah\'s Boat |
Thank you very much you two! The response time was impeccable. |