Static Block
- ทำงานตอน Class Loading (โหลดคลาสเข้าหน่วยความจำ)
- ทำงาน ก่อน main() Method
- ไม่มีชื่อใน Prototype (แค่
static { ... })
- ใช้สำหรับ Logic ที่ต้องรันตอน Class Load (เช่น Load Native Library, Initialize Static Config)
Syntax
static {
// statements
}
ตัวอย่าง Static Block
public class StaticBlockTest {
static {
System.out.println("Static Block!");
}
public static void main(String args[]) {
System.out.println("Welcome to Tutorials Point!");
}
}
ผลลัพธ์
Static Block!
Welcome to Tutorials Point!
Constructor
- ทำงานตอน สร้าง Object (new)
- เรียกตอน Instantiation
- ชื่อ ต้องเหมือนชื่อคลาส
- ทำงาน ทุกครั้งที่ new Object (หลายครั้งได้)
Syntax
public class MyClass {
MyClass() { // Constructor
// statements
}
}
ตัวอย่าง Constructor กับ Static Block
public class ConstructorTest {
static {
System.out.println("In Static Block!");
}
public ConstructorTest() {
System.out.println("In a first constructor!");
}
public ConstructorTest(int c) {
System.out.println("In a second constructor!");
}
public static void main(String args[]) {
ConstructorTest ct1 = new ConstructorTest();
ConstructorTest ct2 = new ConstructorTest(10);
}
}
ผลลัพธ์
In Static Block!
In a first constructor!
In a second constructor!
ตารางเปรียบเทียบ
| คุณสมบัติ | Static Block | Constructor |
| Trigger | Class Loading | Object Creation (new) |
| ความถี่ | ครั้งเดียวต่อ ClassLoader | ทุกครั้งที่ new |
| ชื่อ | ไม่มี (anonymous block) | ต้องเหมือนชื่อ Class |
| เข้าถึงได้ | Static Members เท่านั้น | Static + Instance Members |
| this/super | ใช้ไม่ได้ | ใช้ได้ |
| Return Type | ไม่มี | ไม่มี (แต่คืน Instance) |
| Overloading | ไม่ได้ (มีได้หลายบล็อก แต่วันตามลำดับ) | ได้ (Multiple Constructors) |
ลำดับการ Initialize ทั้งหมด
- Static Variables (ตามลำดับ)
- Static Blocks (ตามลำดับ)
- Instance Variables (ตามลำดับ)
- Non-Static Blocks (ตามลำดับ)
- Constructor Body