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

Return Type ของ Constructor ใน Java คืออะไร


Constructor คล้ายเมธอด เรียกตอนสร้างอ็อบเจกต์ Initialize instance variables ชื่อตรงกับคลาส

Return Type ของ Constructor

  • Constructor ไม่มี Return Type (แม้ void ก็ไม่มี)
  • เมธอดทั่วไป มี return type ระบุชนิดข้อมูลที่คืน
  • Constructor ไม่คืนค่าโดยตรง แต่คืน Instance ของคลาสนั้นๆ ให้ caller โดยอัตโนมัติ

ตัวอย่าง Constructor พื้นฐาน

public class Sample {
    // No-arg constructor
    public Sample() {
        System.out.println("Hello how are you");
    }
    
    // Parameterized constructor
    public Sample(String data) {
        System.out.println(data);
    }
    
    public static void main(String args[]) {
        Sample obj = new Sample("Tutorialspoint");
    }
}

Output

Tutorialspoint

ตัวอย่าง: Constructor สร้างอ็อบเจกต์และคืน Instance

class Student {
    Integer age;
    
    Student(Integer age) {
        this.age = age;
    }
    
    public void display() {
        System.out.println("Value of age: " + this.age);
    }
}

public class GenericsExample {
    public static void main(String args[]) {
        // new Student(25) → เรียก constructor → คืน Student instance → assign ให้ std
        Student std = new Student(25);
        std.display();
    }
}

Output

Value of age: 25

สรุปความแตกต่าง Constructor vs Method

คุณสมบัติConstructorMethod
Return Typeไม่มี (implicit: class instance)ต้องระบุ (void, int, String, etc.)
ชื่อตรงกับ Class Nameอะไรก็ได้ (camelCase)
การเรียกnew ClassName()obj.methodName()
Overrideไม่ได้ (แต่ Overload ได้)Override ได้
Inheritanceไม่สืบทอด (super() เรียก parent)สืบทอดได้

ข้อผิดพลาดที่พบบ่อย

// ❌ ผิด - Constructor มี return type
public void MyClass() { }  

// ❌ ผิด - Constructor คืนค่า
public MyClass() {
    return new MyClass();  // Infinite recursion!
}

// ✅ ถูกต้อง
public MyClass() {
    // initialize fields
}