Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Khác biệt giữa static block và constructor trong Java

Static Block (Khối tĩnh)

  • Thực thi khi nạp lớp (class loading).
  • Chạy trước phương thức main().
  • Không có tên trong prototype.
  • Dùng cho logic cần chạy khi load class (khởi tạo static variable phức tạp, đăng ký driver, load native library).

Cú pháp

static { 
    // statements 
}

Ví dụ Static Block

public class StaticBlockTest { 
    static { 
        System.out.println("Static Block!"); 
    } 
    public static void main(String args[]) { 
        System.out.println("Welcome to Tutorials Point!"); 
    } 
}

Kết quả

Static Block! 
Welcome to Tutorials Point!

Constructor

  • Thực thi khi tạo đối tượng (object creation).
  • Gọi khi tạo instance của lớp.
  • Tên constructor = tên lớp.
  • Chạy mỗi lần new (mỗi object một lần).

Cú pháp

public class MyClass { 
    MyClass() { // constructor 
        // statements 
    } 
}

Ví dụ 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); 
    } 
}

Kết quả

In Static Block! 
In a first constructor! 
In a second constructor!

Bảng so sánh tóm tắt

Đặc điểmStatic BlockConstructor
Thời điểm chạyClass loading (1 lần)Object creation (mỗi new)
Trước main()CóKhông
TênKhông có (anonymous)Trùng tên lớp
Tham sốKhôngCó thể có
OverloadKhôngCó
Truy cập this/superKhôngCó
Dùng choKhởi tạo static field, đăng kýKhởi tạo instance field