Static Method
เป็นของ Class ไม่ใช่ Instance เรียกได้โดยไม่ต้อง new Object (ClassName.method())
ข้อจำกัด (Restrictions)
- เข้าถึง Non-Static Member ไม่ได้ - Instance Variable/Method ต้องมี Object ก่อน (this ไม่มีใน Static Context)
- ใช้ this / super ไม่ได้ - ไม่มี Instance Context
- Override ไม่ได้ - สามารถ Hide (Declare ใหม่ใน Subclass) ได้ แต่ไม่ใช่ Override (Polymorphism ไม่ทำงาน)
- เข้าถึงได้เฉพาะ Static Member (Static Fields, Static Methods)
Static Block
Block โค้ดที่มี static { ... } รันตอน Class Loading (ก่อน main) ใช้ Initialize Static Fields
ข้อจำกัด (Restrictions)
- Return ค่าไม่ได้ - ไม่มี Return Type
- Invoke เองไม่ได้ - รันอัตโนมัติตอน Class Load ตามลำดับที่ประกาศ
- Throw Checked Exception ไม่ได้ - ต้อง Try-Catch ภายใน Block (Unchecked Exception โยนได้)
- ใช้ this / super ไม่ได้ - ไม่มี Instance
- ควบคุมลำดับการรันไดนามิกไม่ได้ - รันตามลำดับ Declaration ใน Class เท่านั้น
ตัวอย่างแสดงข้อจำกัด
public class StaticRestrictions {
static int staticVar = 10;
int instanceVar = 20;
// Static Block
static {
System.out.println("Static Block: " + staticVar); // OK
// System.out.println(instanceVar); // Error: non-static variable cannot be referenced
// return; // Error: cannot return from static block
// throw new IOException(); // Error: checked exception must be caught
try {
// Checked Exception ต้อง Catch ใน Block
} catch (Exception e) {}
}
// Static Method
public static void staticMethod() {
System.out.println("Static Method: " + staticVar); // OK
// System.out.println(instanceVar); // Error
// this.staticVar = 30; // Error: cannot use this in static context
}
// Instance Method (เข้าถึง Static ได้)
public void instanceMethod() {
System.out.println("Instance Method: " + staticVar); // OK
System.out.println(instanceVar); // OK
}
public static void main(String[] args) {
StaticRestrictions.staticMethod();
new StaticRestrictions().instanceMethod();
}
}
ผลลัพธ์
Static Block: 10 Static Method: 10 Instance Method: 10 20
สรุปตาราง
| Context | เข้าถึง Static | เข้าถึง Instance | this/super | Throw Checked Exception |
|---|---|---|---|---|
| Static Method | ✅ | ❌ | ❌ | ✅ (throws) |
| Static Block | ✅ | ❌ | ❌ | ❌ (ต้อง Try-Catch) |
| Instance Method | ✅ | ✅ | ✅ | ✅ (throws) |