สร้าง constructor สำหรับคลาส Car
การกำหนดค่าให้กับ property ของคลาสเป็นสิ่งสำคัญที่ช่วยให้ใช้งานคลาสได้อย่างมีประสิทธิภาพ ในแบบฝึกหัดนี้ คุณจะสร้าง constructor สำหรับคลาส Car และกำหนดค่าเริ่มต้นให้กับ property ต่าง ๆ
จำไว้: constructor ของคลาสจะถูกเรียกใช้เสมอเมื่อมีการสร้าง instance
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
Java เบื้องต้นสำหรับการเขียนโปรแกรมเชิงวัตถุ
คำแนะนำการฝึกหัด
- สร้างเมธอด constructor สำหรับคลาส
Carโดยไม่รับพารามิเตอร์ใด ๆ - ภายใน constructor ให้กำหนดค่า property
colorเป็น String"red" - ภายใน constructor ให้กำหนดค่า
yearเป็น Integer2019 - แสดงค่า property
colorของ object instancemyCar
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
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(____.____);
}
}