เริ่มต้นใช้งานเริ่มต้นใช้งานได้ฟรี

สร้าง constructor สำหรับคลาส Car

การกำหนดค่าให้กับ property ของคลาสเป็นสิ่งสำคัญที่ช่วยให้ใช้งานคลาสได้อย่างมีประสิทธิภาพ ในแบบฝึกหัดนี้ คุณจะสร้าง constructor สำหรับคลาส Car และกำหนดค่าเริ่มต้นให้กับ property ต่าง ๆ

จำไว้: constructor ของคลาสจะถูกเรียกใช้เสมอเมื่อมีการสร้าง instance

แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร

Java เบื้องต้นสำหรับการเขียนโปรแกรมเชิงวัตถุ

ดูคอร์ส

คำแนะนำการฝึกหัด

  • สร้างเมธอด constructor สำหรับคลาส Car โดยไม่รับพารามิเตอร์ใด ๆ
  • ภายใน constructor ให้กำหนดค่า property color เป็น String "red"
  • ภายใน constructor ให้กำหนดค่า year เป็น Integer 2019
  • แสดงค่า property color ของ object instance myCar

แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ

ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์

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(____.____);
  }
}
แก้ไขและรันโค้ด