Constructor ใน Java เป็นรูปแบบหนึ่งของเมธอดแต่แตกต่างที่: ชื่อตรงกับคลาส และ ไม่มี return type
Constructor ถูกเรียก โดยอัตโนมัติ (Implicitly) ตอนสร้างอ็อบเจกต์ (new ClassName()) จุดประสงค์หลัก: Initialize Instance Variables
Syntax
class ClassName {
ClassName() {
// initialization code
}
}
กฎการเขียน Constructor
- ไม่มี return type (ไม่มี void)
- ชื่อต้องตรงกับชื่อคลาส
- ไม่สามารถเป็น abstract, final, static, synchronized ได้
- เข้าถึงได้: public, protected, private, package-private
ตัวอย่าง Constructor พื้นฐาน
public class Test {
int num;
String data;
Test() {
num = 100;
data = "sample";
}
public static void main(String args[]) {
Test obj = new Test();
System.out.println(obj.num);
System.out.println(obj.data);
}
}
Output
100 sample
ประเภท Constructor
| ประเภท | คำอธิบาย | ตัวอย่าง |
|---|---|---|
| No-arg / Default | ไม่รับพารามิเตอร์ | public Test() {} |
| Parameterized | รับพารามิเตอร์ | public Test(int x) {} |
| Copy Constructor | รับอ็อบเจกต์เดียวกัน (Manual) | public Test(Test other) {} |
Constructor Overloading
เขียน Constructor หลายตัวในคลาสเดียวกัน ต่างกันที่ Parameter List
public class Demo {
private int id;
private String name;
public Demo() { this(0, "Unknown"); }
public Demo(int id) { this(id, "Unknown"); }
public Demo(String name) { this(0, name); }
public Demo(int id, String name) { // Primary
this.id = id;
this.name = name;
}
}
Constructor Chaining
this(...)เรียก Constructor อื่นในคลาสเดียวกัน (ต้องเป็น statement แรก)super(...)เรียก Constructor ของ Parent Class (ต้องเป็น statement แรก)
Default Constructor (Implicit)
ถ้าไม่เขียน Constructor ใดๆ Compiler จะสร้าง No-arg Constructor ให้อัตโนมัติ
public class Sample {
// ไม่มี constructor
// Compiler สร้าง: public Sample() { super(); }
}
แต่ถ้าเขียน Constructor เองแม้ 1 ตัว → Compiler ไม่สร้าง Default ให้