開始使用免費開始

建構子多載

建構子就像其他方法一樣,可以透過多型來進行多載。你將編輯 Tesla 類別,加入第二個建構子,接受車輛是否投保的狀態,讓你能用不同的建構子為 Tesla 類別建立多個物件實例。

本練習屬於課程

Java 物件導向程式設計入門

檢視課程

練習說明

  • Tesla 類別完成第二個建構子方法,新增一個額外參數 boolean isInsured
  • 在新的 Tesla 建構子方法內,將類別屬性 isInsured 設為對應的建構子參數。
  • 使用新的建構子方法建立 Tesla 類別的第二個物件實例 mySecondTesla,並傳入參數 "modelY""black"、以及 false

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

public class Main {
    
    static class Tesla {
        public String model;
        public String color;
        public boolean isInsured;
        
       public Tesla(String model, String color){
           this.model = model;
           this.color = color;
       }
       
       // Complete second constructor
        public ____(String model, String color, ____ ____){
           this.model = model;
           this.color = color;
           // Set the isInsured property
           ____.____ = ____;
       }
       
    }

    public static void main(String[] args) {
        Tesla myFirstTesla = new Tesla("modelX", "red");
        // Create object instance with second constructor
        ____ mySecondTesla = new ____("____", "black", ____);
    }
}
編輯並執行程式碼