为什么一个空白 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

更新于: 2019 年 10 月 15 日

1K+ 次浏览

开启您的 职业生涯

通过完成课程获得认证

开始
广告
© . All rights reserved.