我想创建我的对象car的实例。我的问题是我可以创建汽车对象的实例,例如Car car1 = new car(“ Audi”,“ A4”,“ BF10YMR”);但是我想通过助手类来创建汽车对象。我该如何在main中将该助手类称为car类而不是carHelper类?
汽车对象需要创建一个随机的注册号,并且该注册号是在carHelper类中创建的。返回对象。
public class Car implements Comparable<Car>
{
public class Car
{
private String make;
private String model;
private String registration;
public Car(String make, String model, String reg)
{
this.make= make;
this.model= model;
registration = reg;
}
}
public class carHelper
{
public car genCar()
{
String reg = //some method to generate random registration.
String Make = //some method to randomly pick make from a list
String model = //some method to randomly pick model from a list
return new Car(make,model,registration);
}
}
public class Garage
{
public static void main (String args[])
{
Garage MyGarage = new Garage();
Car car1 = new Car("Audi","A4","BF10YMR") //works, but doesn't use helper
Car car2 = carHelper.genCar(); // something like this?
carHelper c = new carHelper(); // thought something like this but
System.out.println(c.genCar()); // creates object of type carHelper
// not car.
MyGarage.add(car1);
MyGarage.add(car2); // gives me carHelper cannot be converted to Car
}
}
public class GarageOp implements CarList
{
public GarageOp()
{
list = new ArrayList<Car>();
}
public boolean add(Car car)
{
if (list.contains(car) == false)
{
list.add(car);
return true;
}
}
}
预期结果是使用helper类创建汽车对象,并将其添加到ArrayList中。
答案 0 :(得分:1)
您可以在CarHelper中创建此列表,然后随机选择值并使用它们创建新的Car。 UUID会创建一个随机的128位(包括十六进制)数字并转换为字符串
public class CarHelper {
private List<String> makeList = Arrays.asList("s", "t", "f", "n");
private List<String> modelList = Arrays.asList("yyt", "32g", "dc3", "aas");
public Car genCar() {
String reg = UUID.randomUUID().toString();
String make = makeList.get(new Random().nextInt(makeList.size() - 1));
String model = modelList.get(new Random().nextInt(modelList.size() - 1));
return new Car(make,model,reg);
}
}
答案 1 :(得分:-1)
在CarHelper类中使genCar()方法为Static。
public car static genCar(){
// do stuff to create object
}
非静态方法可以访问静态变量或在Java中调用静态方法。