為車輛類別建立建構子
能夠為類別的屬性設定數值,才能有效使用它們。你將為 Car 類別建立一個建構子,並確保它的屬性被設定為適當的數值。
請記住:當我們建立實例時,類別的建構子一定會被呼叫。
本練習屬於課程
Java 物件導向程式設計入門
練習說明
- 為
Car類別建立一個不帶參數的建構子方法。 - 在建構子裡,將
color屬性設為字串"red"。 - 在建構子裡,將
year設為整數2019。 - 列印
myCar物件實例的color屬性。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
class Main {
static class Car {
String color;
String model;
int year;
// Create constructor method
____() {
this.model = "camry";
// Assign the values for the color and year properties
____.____ = "____";
____.____ = ____;
}
}
public static void main(String[] args) {
Car myCar = new Car();
// Print the "color" property
System.out.println(____.____);
}
}