開始使用免費開始

為車輛類別建立建構子

能夠為類別的屬性設定數值,才能有效使用它們。你將為 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(____.____);
  }
}
編輯並執行程式碼