I have a class called Car, 6 other classes (Van,Cab,Truck, Taxi, Sedan and Motorbike) that implement this class. Each of the subclasses has its own mnethods and attributes.

How would I go about creating an array of these vehicles with the type of car being randomly selected. that is I would like to have an array that looks like this

ArrayLaneSouth = {Van,Cab, Taxi, Sedan}
ArrayLaneNorth = {Van,Cab, Taxi, Sedan}
ArrayLaneWest = {Van,Cab, Taxi, Sedan}
ArrayLaneEast = {Van,Cab, Taxi, Sedan}

the elements in the arrays are types of cars and the type be selected randomly.

1 Year
Discussion Span
Last Post by liphoso

classes can't 'implement' classes, only extend them. Unless of course Car is an interface, not a class.
basically, this can be done with (a bit) the same logic as ye olde "roll the dice".

in here, the possible values are not "1-2-3-4-5-6", but, let's say you have an array of existingTypes:

String[] existingTypes = {"Van", "Cab", "Taxi", "Sedan"};

Here, your possible values are: "0-1-2-3", the valid indices of your array.

Based on the information you can find here: http://stackoverflow.com/questions/12860398/basic-random-rolling-dice-java

you can easily write a method getRandomIndex() that returns a random index for you to use.

then you can implement something like:

Car[] newArray = new Car[x]; // x being the number of elements you want.
for ( int i = 0; i < x; i++){
  case 0: newArray[i] = new Van();
  case 1: newArray[i] = new Cab();
  case 2: newArray[i] = new Taxi();
    case 3:
    default: newArray[i] = new Sedan();

No need for the Strings or the switch, classes are Classes in their own right!

Class[] carTypes = {Van.class, Cab.class ... };
for ( int i = 0; i < x; i++) {
   newArray[i] = (Car) carTypes[getRandomIndex()].newInstance();

Edited by JamesCherrill

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.