dimanche 28 mars 2021

If my class has many children, how can I initialize an object that is a random child of my class?

For example.

Parent: Vehicle Children: Car, Train, Horse

I want to do the following

Vehicle randVehicle = new RandomeVehicleChildObject;

I was thinking I could do this:

Vehicle randVehicle;
Random r = new Random();
int x = r.nextInt();

if(x == someInt)
   randVehicle = new Car();
else if(x == otherNum)
   randVehicle = new Train();
else
   randVehicle = new Horse();

However, what if my class has many more children? Like 15 or 20? I feel like writing so many if-else chains or switches would be a pain. Is there a way to just do it in one line?




Aucun commentaire:

Enregistrer un commentaire