gpt4 book ai didi

java - 调用多个构造函数 - 只调用同一个构造函数?

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:20:41 24 4
gpt4 key购买 nike

我是 Java 的新手,我搞不懂这个。我试过在我的对象的参数中传递值,但它只想转到没有参数的构造函数。其他 2 个有多个参数,但它没有注意到它?提前致谢!

代码如下:

    Car vehicle1 = new Car();
Car vehicle2 = new Car();
Car vehicle3 = new Car();

public Car() {

private int numberOfCars;

private String company;
private String modelName;
private String modelYear;
private double hp;
private int doors;
private String gears;
private String color;
private boolean racingCar;
private double price;

numberOfCars = -1;
company = "***EMPTY***";
modelName = "***EMPTY***";
modelYear = "***EMPTY***";
hp = -1;
doors = -1;
gears = "***EMPTY***";
color = "***EMPTY***";
racingCar = false;
price = -1;
}
public Car(String companyName, String modelNa, String modelYe){

numberOfCars = -1;
company = companyName;
modelName = modelNa;
modelYear = modelYe;
hp = -1;
doors = -1;
gears = "***EMPTY***";
color = "***EMPTY***";
racingCar = false;
price = -1;
}
public Car(int carAmount, String companyTitle, String modelTitle, String modelBirth, double horsePower, int door, String gearType, String colors, boolean raceCar, double prices){

numberOfCars = carAmount;
company = companyTitle;
modelName = modelTitle;
modelYear = modelBirth;
hp = horsePower;
doors = door;
gears = gearType;
color = colors;
racingCar = raceCar;
price = prices;
}

最佳答案

为了调用其他构造函数,您需要在构建对象时指定参数:

Car vehicle1 = new Car();
Car vehicle2 = new Car("companyName", "modelNa", "modelYe");
Car vehicle3 = new Car(2, "companyTitle", "modelTitle", "modelBirth", 5.2, 4, "gearType", "colors", false, 1600);

关于java - 调用多个构造函数 - 只调用同一个构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29725031/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com