為什麼一個空白 final 變數在所有 Java 建構函式中都應顯式初始化?
未初始化的 final 變數稱為空白 final 變數。
通常,我們在建構函式中初始化例項變數。如果我們錯過了它們,建構函式將使用預設值對它們進行初始化。但是,空白 final 變數不會用預設值進行初始化。所以如果你嘗試在建構函式中不初始化就使用一個空白 final 變數,就會產生編譯時錯誤。
示例
public class Student { public final String name; public void display() { System.out.println("Name of the Student: "+this.name); } public static void main(String args[]) { new Student().display(); } }
編譯時錯誤
在編譯時,此程式會生成以下錯誤。
Student.java:3: error: variable name not initialized in the default constructor private final String name; ^ 1 error
因此,一旦你宣告 final 變數就必須對其進行初始化。如果類中提供了多個建構函式,則你需要在所有建構函式中初始化空白 final 變數。
示例
public class Student { public final String name; public Student() { this.name = "Raju"; } public Student(String name) { this.name = name; } public void display() { System.out.println("Name of the Student: "+this.name); } public static void main(String args[]) { new Student().display(); new Student("Radha").display(); } }
輸出
Name of the Student: Raju Name of the Student: Radha
廣告