为 Car 类创建构造方法
能够为类的属性设置取值非常重要,只有这样才能有效使用这些属性。请为 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(____.____);
}
}