ไม่ได้ Java ไม่รองรับ Static Constructor ถ้าพยายามประกาศ Constructor ด้วย static จะเกิด Compile-time Error
เหตุผล
- Static = ระดับคลาส (Class-level) ใช้ร่วมกันทุกอินสแตนซ์
- Constructor = ใช้ Initialize Instance Variables (ระดับอินสแตนซ์)
- ทั้งคู่ ขัดแย้งกัน (Opposite concepts)
ตัวอย่างที่ Error
public class StaticConstructorTest {
int x = 10;
// Static Constructor - INVALID!
static StaticConstructorTest() {
System.out.println("Static Constructor");
}
public static void main(String args[]) {
StaticConstructorTest sct = new StaticConstructorTest();
}
}
Error Message
StaticConstructorTest.java:4: error: modifier static not allowed here
static StaticConstructorTest() {
^
1 error
ทางเลือก: Static Initialization Block
ใช้ Static Block แทน สำหรับ Initialize Static Variables
public class StaticBlockExample {
static int x;
static String name;
// Static Block - รันตอน Class Loading (ครั้งเดียว)
static {
x = 10;
name = "Initialized in Static Block";
System.out.println("Static Block Executed");
}
public StaticBlockExample() {
System.out.println("Constructor Called");
}
public static void main(String[] args) {
System.out.println("Main Started");
new StaticBlockExample();
new StaticBlockExample();
}
}
ผลลัพธ์
Static Block Executed
Main Started
Constructor Called
Constructor Called
สรุป
| ความต้องการ | ใช้ |
|---|---|
| Initialize Instance Variables | Constructor (Instance) |
| Initialize Static Variables / Logic ตอน Class Load | Static Block |
| Static Constructor | ไม่มีใน Java |