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

ความแตกต่างระหว่าง Static Block และ Constructor ใน Java

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 BlockConstructor
TriggerClass LoadingObject Creation (new)
ความถี่ครั้งเดียวต่อ ClassLoaderทุกครั้งที่ new
ชื่อไม่มี (anonymous block)ต้องเหมือนชื่อ Class
เข้าถึงได้Static Members เท่านั้นStatic + Instance Members
this/superใช้ไม่ได้ใช้ได้
Return Typeไม่มีไม่มี (แต่คืน Instance)
Overloadingไม่ได้ (มีได้หลายบล็อก แต่วันตามลำดับ)ได้ (Multiple Constructors)

ลำดับการ Initialize ทั้งหมด

  1. Static Variables (ตามลำดับ)
  2. Static Blocks (ตามลำดับ)
  3. Instance Variables (ตามลำดับ)
  4. Non-Static Blocks (ตามลำดับ)
  5. Constructor Body