为什么要在所有Java构造函数中显式初始化空白的final变量?
没有初始化的最终变量称为空白最终变量。
通常,我们在构造函数中初始化实例变量。如果我们错过了它们,它们将由构造函数初始化为默认值。但是,最终的空白变量将不会使用默认值初始化。因此,如果您尝试使用空白的最终变量而不在构造函数中进行初始化,则会生成编译时错误。
示例
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
热门推荐
10 圣诞祝福语简短小学
11 祖国七十华诞简短祝福语
12 老师送的祝福语简短
13 生日祝福语大全女生简短
14 祝女性生日祝福语简短
15 牛年女神节祝福语简短
16 情人表白祝福语简短大气
17 老公开业祝福语简短
18 官宣新年祝福语简短