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

Tại sao Java không cho phép khởi tạo biến static final trong constructor?

Biến static final (constant) phải được khởi tạo tại chỗ khai báo hoặc trong static block. Nếu bạn thử gán giá trị trong constructor, compiler hiểu đó là việc gán lại (reassignment) cho biến final đã có giá trị mặc định → báo lỗi compile time.

Ví dụ sai: Khởi tạo trong constructor

class Data {
    static final int NUM;
    
    Data(int i) {
        NUM = i; // Compile error: cannot assign a value to final variable NUM
    }
}

public class ConstantsExample {
    public static void main(String args[]) {
        System.out.println("value of the constant: " + Data.NUM);
    }
}
ConstantsExample.java:4: error: cannot assign a value to final variable NUM
    NUM = i;
    ^

Đúng: Khởi tạo trong static block

class Data {
    static final int NUM;
    
    static { // Static initialization block
        NUM = 1000; // OK
    }
}

public class ConstantsExample {
    public static void main(String args[]) {
        System.out.println("value of the constant: " + Data.NUM);
    }
}
value of the constant: 1000

Tại sao Java thiết kế như vậy?

  1. Static = class-level: Khởi tạo khi class load, trước khi bất kỳ object nào được tạo. Constructor chạy sau khi class đã load xong.
  2. Final = không đổi: Giá trị phải xác định được tại class loading time.
  3. Constructor gắn liền với instance, không phù hợp để khởi tạo biến class-level.

Best practice: Khởi tạo static final ngay tại dòng khai báo nếu là hằng số đơn giản. Dùng static block nếu logic khởi tạo phức tạp (cần try-catch, vòng lặp, v.v.).