为什么在所有 Java 构造函数中都要显式初始化空白 final 变量?
javaobject oriented programmingprogramming更新于 2024/8/26 11:14:00
未初始化的 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