aspose file tools*
The moose likes Beginning Java and the fly likes Creating an object of a random subclass Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Creating an object of a random subclass" Watch "Creating an object of a random subclass" New topic
Author

Creating an object of a random subclass

Belen Garcia
Greenhorn

Joined: May 16, 2011
Posts: 3
Hi, I have been learning java for a couple of weeks, and I am having some problems:

I have an abstract class "animal", and several subclasses (dog, cat, cow...). From my main class, I would like to make and instance of one of the subclasses, randomly chosen.
How can I make that ?

Thanks!
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 60975
    
  65

Seems a bit advanced for a couple of weeks of Java. But, you can use the Math class to generate a random number. Then use it to pick one of the subclasses to create.

For now, you can use a switch statement, but as you get more advanced, Java reflection could simplify the code.


[Asking smart questions] [Bear's FrontMan] [About Bear] [Books by Bear]
Belen Garcia
Greenhorn

Joined: May 16, 2011
Posts: 3
Thank you for fast replay.

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).

Ralph Cook
Ranch Hand

Joined: May 29, 2005
Posts: 479
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.

rc

Belen Garcia
Greenhorn

Joined: May 16, 2011
Posts: 3
Thanks a lot for your help. I´m using that Class.forName() method, and it´s working great.

Belen
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Creating an object of a random subclass