In: Computer Science
1, Create a class Car. The class has four instance fields:
Provide
2. Create a class CarFactory
It provides just one method public static Car createRandomCar() which creates a random car instance with value chosen from the admissible set/range.
// PLEASE LIKE THE SOLUTION
// FEEL FREE TO DISCUSS IN COMMENT SECTION
// JAVA PROGRAM
import java.util.*;
//Car class
class Car{
// properties
private String make;
private String size;
private int weight;
private int horsePower;
// constructor default
Car(){
make = null;
size = null;
weight=0;
horsePower=0;
}
// param constructor
Car(String make,String size,int weight,int
horsePower){
this.make = make;
this.size = size;
this.weight = weight;
this.horsePower = horsePower;
}
// setters
public void setMake(String make){
this.make = make;
}
public void setSize(String size){
this.size = size;
}
public void setWeight(int weight){
this.weight = weight;
}
public void setHorsePower(int horsePower){
this.horsePower = horsePower;
}
// getters
public String getMake(){
return this.make;
}
public String setSize(){
return this.size;
}
public int setWeight(){
return this.weight;
}
public int setHorsePower(){
return this.horsePower;
}
// to String method
public String toString(){
return ("Make = "+(this.make)+"
Size = "+(this.size)+" Weight = "+(this.weight)+" HorsePower =
"+(this.horsePower));
}
}
// class CarFactory
class CarFactory{
// static method
public static Car createRandomCar(){
// array to store permissible
values
String makeArray[] =
{"Chevy","Ford","Toyota","Nissan","Hyundai"};
String sizeArray[] =
{"compact","intermediate","fullSized"};
// create instance of Random
class
Random rand = new Random();
// Generate random integers in
range 0 to 4
int makevalue =
rand.nextInt(5);
// Generate random integers in
range 0 to 2
int sizevalue =
rand.nextInt(3);
// generate random 500 to
4000
int weight =
rand.nextInt(3501)+500;
// generate random 30 to
400
int horsePower =
rand.nextInt(401)+30;
// call constructor
Car car=new
Car(makeArray[makevalue],sizeArray[sizevalue],weight,horsePower);
return car;
}
// main method for testing
public static void main(String arg[]){
Car car = createRandomCar();
System.out.println(car);
}
}
// SAMPLE OUTPUT