创建私有属性
为了限制外部访问,类的属性通常会设为私有。例如,在 Passport 类中,某些字段只能在特定条件下设置。您将把 Car 类中汽车的登记号码设为私有,以对其进行隐藏。
本练习是课程的一部分
Java 面向对象编程入门
练习说明
- 新增一个名为
vehicleNumber的private属性,类型为int。
交互式实操练习
通过完成这段示例代码来试试这个练习。
class Main {
static class Car {
public String color;
public String model;
public int year;
// Create private property "vehicleNumber"
____ ____ ____;
Car(String color, String model, int year) {
this.color = color;
this.model = model;
this.year = year;
this.vehicleNumber = 101189;
}
public void turnEngineOn() {
System.out.println("engine is on");
}
public int calculateMPG(int milesDriven, int gallonsUsed) {
return milesDriven / gallonsUsed;
}
}
public static void main(String[] args) {
}
}