开始使用免费开始使用

构造函数重载

构造函数与其他方法一样,可以通过多态实现重载。您将编辑 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", ____);
    }
}
编辑并运行代码