There are 3 classes of Car, Bycicle and Bike; It is necessary to fill an array of 10 cells with random objects of these classes.
3 answers
It is not necessary to inherit classes from some general class: they all inherit Object
. The easiest option (not the best from the point of view of practical use, but well solving the task):
public static Object[] fill() { Object[] array = new Object[10]; Object obj = null; Random randomizer = new Random(); for (int i=0; i<10; i++) { int randomNumber = randomizer.nextInt(3); switch(randomNumber) { case 0: obj = new Car(); break; case 1: obj = new Bicycle(); break; case 2: obj = new Bike(); break; } array[i] = obj; } return array; }
Method to test:
public static void main(String[] args) { for (Object o:fill()) { System.out.println(o); } }
The output to the screen (the classes I have nested in the class ComplexNumber
):
com.company.ComplexNumber$Bicycle@677327b6 com.company.ComplexNumber$Bike@14ae5a5 com.company.ComplexNumber$Car@7f31245a com.company.ComplexNumber$Car@6d6f6e28 com.company.ComplexNumber$57555 $ Bike @ 45ee12a7 com.company.ComplexNumber$Bicycle@330bedb4 com.company.ComplexNumber$Bicycle@2503dbd3 com.company.ComplexNumber$Bike@4b67cf4d com.company.ComplexNumber$Bicycle@7ea987ac
It can be seen that the array is filled with objects of different classes.
In each class there are fields that are reduced to primitive types in the end. You need for each class field, if it is a primitive, then generate it, if not a primitive, generate the primitives that make up this object. And so on. I believe that you have a little field at all and it will be easy. How to generate a random string, you can look for example here or here . If you need a random string or a value from some set, then usually put this set into some variable, and then choose a value from the set by a randomly generated index.
Make the Vehicle
class with common attributes from existing classes. Inherit Car
, Bycicle
and Bike
from Vehicle
.
Create a method in the Vehicle
class rand
method where, according to some condition, memory allocation of one or another heir class will be performed.
Create the Vehicle
array and re-allocate the memory in a loop.
Example
Car
class:
public class Car extends Vehicle { Car(){ super(200); }; }
Bike
class:
public class Bike extends Vehicle { Bike(){ super(80); } }
Vehicle
class
import java.util.Random; public class Vehicle { int maxSpeed; Vehicle(int m ){ this.maxSpeed=m; } static public Vehicle rand(){ Random rand= new Random(); Vehicle v; if (rand.nextBoolean()) v = new Car(); else v= new Bike(); return v; } public static void main(String[] args) { Vehicle v[] = new Vehicle[10]; for (int i = 0; i < 10; i++) { v[i]=Vehicle.rand(); System.out.println(i+" "+v[i].maxSpeed); } } }
Result:
[0-200] [1-80] [2-80] [3-200] [4-200] [5-80] [6-200] [7-80] [8-200] [9-80]