This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
The problem is that, if I use a switch statement, then I suppose I have to list my subclasses in my main class (or list them in an array or something like that). Then, if some day I add more subclasses (more animals), I´ll have to change that switch statement.
I don´t know if there is a way for a program, in runtime, to get to know how many subclasses of a given class has, so then I can choose one with a Random number. I´m going to read about reflection, my be that´s what I need (I have no idea of what it is).
You can also use the Class.forName() method; it allows for creating an instance of a class by its (fully-qualified) name. You could put the names of your subclasses in an array, use Math.random to generate a random number that is an index into that array, and instantiate the result.
You could go further and put the classnames into a file; then you could write a new subclass, add to the file, and it becomes part of the program. You're going to need to learn about package structure and where to put the new class file after you've compiled it.
Class someAnimalClass = Class.forName(animalNameArray[randomNumber]);
Animal someAnimal = someAnimalClass.newInstance();
This is like reflection, but doesn't get into the complexities of the reflection API. You will, of course, be restricted to using methods that are defined in Animal.
Joined: May 16, 2011
Thanks a lot for your help. I´m using that Class.forName() method, and it´s working great.
I’ve looked at a lot of different solutions, and in my humble opinion Aspose is the way to go. Here’s the link: http://aspose.com