我一直在想如何正確地將這些屬性從數據類傳遞給可執行類,但是我不知道如何。這裏是數據類:在Java中引用屬性的問題
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我得到一個錯誤,當我嘗試從後在電機增加對汽缸,馬力和類型的值:
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:未解決的編譯問題: 構造函數Vehicle(String,String,int,double,int,int,String)未定義
非常感謝!