초기화 없이 남겨진 최종 변수를 빈 최종 변수라고 합니다. .
일반적으로 생성자에서 인스턴스 변수를 초기화합니다. 놓치면 기본 값으로 생성자에 의해 초기화됩니다. 단, 마지막 공백 변수는 기본값으로 초기화되지 않습니다. 따라서 생성자에서 초기화하지 않고 빈 최종 변수를 사용하려고 하면 컴파일 시간 오류가 발생합니다.
예
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
따라서 최종 변수를 선언한 후에는 반드시 초기화해야 합니다. 클래스에 둘 이상의 생성자가 제공되는 경우 모든 생성자에서 빈 최종 변수를 초기화해야 합니다.
예
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