gpt4 book ai didi

java - Java 中引用属性的问题

转载 作者:行者123 更新时间:2023-12-01 18:11:24 25 4
gpt4 key购买 nike

我一直在试图弄清楚如何将这些属性从数据类正确传递到可执行类,但我不确定如何。这是数据类:

public class Motor {
private int cylinders;
private int hp;
private String type;
public Motor(int cylinders, int hp, String type) {
this.cylinders = cylinders;
this.hp = hp;
this.type = type;
}
public int getCylinders() {
return cylinders;
}
public int getHp() {
return hp;
}
public String getType() {
return type;
}
public String toString() {
return "Motor: cylinders=" + this.cylinders + ", hp=" +
this.hp + ", type=" + this.type;
}
}

现在,在另一个数据类中,我应该引用 Motor 并创建一堆其他属性。我对此没有任何(明显的)错误,但我认为如果我不发布它,这些都没有任何意义:

public class Vehicle {
private String make;
private String model;
private int year;
private double price;
private Motor motor;
public Vehicle(String make, String model, int year, double price, Motor motor) {
this.make = make;
this.model = model;
this.year = year;
this.price = price;
this.motor = motor;

}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String toString() {
return "Vehicle make=" + this.make + ", model=" +
this.model + ", year=" + this.year +
", price=" + this.price + ", motor=" +
this.motor;
}
}

真正的问题是,当我在 TestVehicle 中创建 Vehicle 对象时,当我尝试在 Motor 中添加汽缸、马力和类型的值时,出现错误:

public class TestVehicle {

public static void main(String[] args) {
Vehicle v1 = new Vehicle("Toyota", "Corolla", 2015, 15999.0, 7, 300, "Gas");
System.out.println(v1.toString());

}

}

当我尝试执行它时出现的错误是:线程“main”java.lang.Error中出现异常: Unresolved 编译问题: 构造函数 Vehicle(String, String, int, double, int, int, String) 未定义

非常感谢!

最佳答案

Exception in thread "main" java.lang.Error: Unresolved compilation problem: The constructor Vehicle(String, String, int, double, int, int, String) is undefined

 Vehicle v1 = new Vehicle("Toyota", "Corolla", 2015, 15999.0, 7, 300, "Gas");

更改为

Motor motor = new Motor( 7, 300, "Gas");
Vehicle v1 = new Vehicle("Toyota", "Corolla", 2015, 15999.0, motor);

检查构造函数。

关于java - Java 中引用属性的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32746519/

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