การสร้าง property แบบ private
โดยทั่วไป property ของคลาสมักถูกกำหนดเป็น private เพื่อป้องกันการเข้าถึงจากภายนอก ตัวอย่างเช่น ในคลาส Passport บางฟิลด์ควรถูกกำหนดค่าได้เฉพาะในเงื่อนไขที่กำหนดเท่านั้น ในแบบฝึกหัดนี้ คุณจะทำให้หมายเลขทะเบียนรถเป็น private ในคลาส Car เพื่อซ่อนข้อมูลนั้นไว้
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
Java เบื้องต้นสำหรับการเขียนโปรแกรมเชิงวัตถุ
คำแนะนำการฝึกหัด
- สร้าง property แบบ
privateชื่อvehicleNumberที่มีชนิดข้อมูลเป็น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) {
}
}