Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Creating an object of a random subclass

 
Belen Garcia
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 65115
89
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Belen Garcia
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 479
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot for your help. I´m using that Class.forName() method, and it´s working great.

Belen
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic