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