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

Constructor Overloading

เราสามารถใช้ Polymorphism เพื่อ overload constructor ได้เหมือนกับเมธอดทั่วไป ในแบบฝึกหัดนี้ จะได้แก้ไขคลาส Tesla ให้มี constructor ตัวที่สอง ซึ่งรับสถานะการประกันภัยของรถเป็น parameter เพื่อให้สามารถสร้าง object instance ของคลาส Tesla ได้หลายแบบโดยใช้ constructor ที่ต่างกัน

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

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

ดูคอร์ส

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

  • เติม constructor ตัวที่สองของคลาส Tesla ให้รับ parameter เพิ่มเติมเป็น boolean ชื่อ isInsured
  • ภายใน constructor ตัวใหม่ของคลาส Tesla กำหนดค่า property isInsured ให้ตรงกับ parameter ที่รับเข้ามา
  • สร้าง object instance ตัวที่สองของคลาส Tesla ชื่อ mySecondTesla โดยใช้ constructor ตัวใหม่ และส่ง "modelY", "black" และ false เป็นค่า parameter

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

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

public class Main {
    
    static class Tesla {
        public String model;
        public String color;
        public boolean isInsured;
        
       public Tesla(String model, String color){
           this.model = model;
           this.color = color;
       }
       
       // Complete second constructor
        public ____(String model, String color, ____ ____){
           this.model = model;
           this.color = color;
           // Set the isInsured property
           ____.____ = ____;
       }
       
    }

    public static void main(String[] args) {
        Tesla myFirstTesla = new Tesla("modelX", "red");
        // Create object instance with second constructor
        ____ mySecondTesla = new ____("____", "black", ____);
    }
}
แก้ไขและรันโค้ด