没有初始化的最终变量称为空白最终变量。
通常,我们在构造函数中初始化实例变量。如果我们错过了它们,它们将由构造函数初始化为默认值。但是,最终的空白变量将不会使用默认值初始化。因此,如果您尝试使用空白的最终变量而不在构造函数中进行初始化,则会生成编译时错误。
public class Student {
   public final String name;
   public void display() {
      System.out.println("学生姓名: "+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变量。
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("学生姓名: "+this.name);
   }
   public static void main(String args[]) {
      new Student().display();
      new Student("Radha").display();
   }
}输出结果
学生姓名: Raju 学生姓名: Radha