Biến static (class variable) thuộc về class, không thuộc instance. Chúng được load vào bộ nhớ lúc compile time, truy cập được mà không cần tạo object.
Khởi tạo trong constructor - Được phép
Nếu biến static không phải final, bạn có thể gán giá trị trong constructor:
public class DefaultExample {
static String name;
static int age;
DefaultExample() {
name = "Krishna";
age = 25;
}
public static void main(String args[]) {
new DefaultExample(); // Gọi constructor để khởi tạo
System.out.println(DefaultExample.name); // Krishna
System.out.println(DefaultExample.age); // 25
}
}
Krishna 25
Nhưng KHÔNG được với static final
Biến static final (constant) bắt buộc khởi tạo tại declaration hoặc trong static block. Không thể gán trong constructor.
Sai: Gán trong constructor
public class DefaultExample {
static final String name;
static final int age;
DefaultExample() {
name = "Krishna"; // Compile error!
age = 25; // Compile error!
}
}
DefaultExample.java:5: error: cannot assign a value to final variable name DefaultExample.java:6: error: cannot assign a value to final variable age
Đúng: Khởi tạo tại declaration hoặc static block
class Data {
static final int NUM; // blank final static
static { // Static initialization block
NUM = 1000;
}
}
Tóm tắt:
static(non-final): Có thể gán trong constructor, nhưng không khuyến khích (gây nhầm lẫn). Nên dùng static block.static final: BẮT BUỘC khởi tạo tại declaration hoặc static block. Constructor KHÔNG được phép.