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ểm | Static Block | Constructor |
| Thời điểm chạy | Class loading (1 lần) | Object creation (mỗi new) |
| Trước main() | Có | Không |
| Tên | Không có (anonymous) | Trùng tên lớp |
| Tham số | Không | Có thể có |
| Overload | Không | Có |
| Truy cập this/super | Không | Có |
| Dùng cho | Khởi tạo static field, đăng ký | Khởi tạo instance field |