Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

วิธีสร้าง Default Constructor (No-arg Constructor) ใน Java


Default Constructor (No-arg Constructor)

Constructor ที่ไม่รับพารามิเตอร์ จะกำหนดค่าเริ่มต้นให้ตัวแปรอินสแตนซ์:

  • อ็อบเจกต์ → null
  • float, double → 0.0
  • boolean → false
  • byte, short, int, long → 0

Constructor ถูกเรียกอัตโนมัติเมื่อสร้างอ็อบเจกต์ (new ClassName())

กฎสำคัญของ Constructor

  • ไม่มี return type (แม้ void ก็ไม่มี)
  • ชื่อต้องตรงกับชื่อคลาส
  • ไม่สามารถเป็น abstract, final, static, synchronized ได้
  • เข้าถึงได้: public, protected, private, package-private

ตัวอย่างที่ 1: ใช้ Default Constructor แบบ Implicit (Compiler สร้างให้)

class NumberValue {
    private int num;
    
    public void display() {
        System.out.println("The number is: " + num);
    }
}

public class Demo {
    public static void main(String[] args) {
        NumberValue obj = new NumberValue();  // ใช้ default constructor
        obj.display();
    }
}

ผลลัพธ์

The number is: 0

ตัวอย่างที่ 2: เขียน Default Constructor เอง (Explicit)

public class Student {
    public final String name;
    public final int age;
    
    // Default constructor - กำหนดค่าเริ่มต้นเอง
    public Student() {
        this.name = "Raju";
        this.age = 20;
    }
    
    public void display() {
        System.out.println("Name of the Student: " + this.name);
        System.out.println("Age of the Student: " + this.age);
    }
    
    public static void main(String args[]) {
        new Student().display();
    }
}

ผลลัพธ์

Name of the Student: Raju
Age of the Student: 20

⚠️ จุดสำคัญ

  • ถ้าเขียน Constructor ใดๆ เอง (แม้แค่ parameterized) → Compiler จะไม่สร้าง default constructor ให้
  • ถ้าต้องการทั้ง default และ parameterized → ต้องเขียน ทั้งสองอย่าง เอง
  • ใช้ this() เรียก constructor อื่นในคลาสเดียวกันได้

ตัวอย่าง: เขียนทั้งคู่

public class Student {
    private String name;
    private int age;
    
    // Default constructor (ต้องเขียนเองเพราะมี parameterized constructor)
    public Student() {
        this("Unknown", 0);  // เรียก parameterized constructor
    }
    
    // Parameterized constructor
    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }
}