為 Java 中的 static final 變數分配值\n
在 Java 中,可以在兩個地方為非 static final 變數分配值。
宣告時。
在建構函式中。
舉例
public class Tester { final int A; //Scenario 1: assignment at time of declaration final int B = 2; public Tester() { //Scenario 2: assignment in constructor A = 1; } public void display() { System.out.println(A + ", " + B); } public static void main(String[] args) { Tester tester = new Tester(); tester.display(); } }
輸出
1, 2
但如果是 static final,則不能在建構函式中分配變數。編譯器將丟擲編譯錯誤。static final 變數需要在 static 塊或宣告時分配。因此,可以在以下兩個位置為 static final 變數分配值。
宣告時。
在 static 塊中。
舉例
public class Tester { final int A; //Scenario 1: assignment at time of declaration final int B = 2; public Tester() { //Scenario 2: assignment in constructor A = 1; } public void display() { System.out.println(A + ", " + B); } public static void main(String[] args) { Tester tester = new Tester(); tester.display(); } }
輸出
1, 2
static final 變數有這種行為的原因很簡單。static final 在各個物件中都是通用的,如果允許在建構函式中分配它,那麼在建立物件時,這個變數會隨著每個物件而改變,因此它不能一次性分配。
廣告