변수를 final로 선언하면 초기화 후에는 그 값을 더 이상 수정할 수 없습니다. 또한 인스턴스 변수와 마찬가지로 최종 변수는 기본값으로 초기화되지 않습니다.
따라서 최종 변수를 선언한 후에는 반드시 초기화해야 합니다 . 그렇지 않으면 컴파일 시간 오류가 생성됩니다.
예시
public class FinalExample {
final int j;
public static void main(String args[]){
FinalExample obj = new FinalExample();
System.out.println(obj.j);
}
} 컴파일 시간 오류
FinalExample.java:5: error: non-static variable j cannot be referenced from a static context System.out.println(j); ^ 1 error
최종 변수 초기화
4가지 방법으로 최종 변수를 초기화할 수 있습니다 -
선언하는 동안.
public class FinalExample {
final int j = 100;
public static void main(String args[]){
FinalExample obj = new FinalExample();
System.out.println(obj.j);
}
} 출력
100
최종 방법 사용.
import java.util.Scanner;
public class FinalExample {
final int num = getNum();
public static final int getNum() {
System.out.println("Enter the num value");
return new Scanner(System.in).nextInt();
}
public static void main(String args[]){
FinalExample obj = new FinalExample();
System.out.println(obj.num);
}
} 출력
Enter the num value 20 20
생성자 사용
public class FinalExample {
final int num;
public FinalExample(int num) {
this.num = num;
}
public static void main(String args[]){
FinalExample obj = new FinalExample(20);
System.out.println(obj.num);
}
} 출력
20
인스턴스 초기화 블록 사용
public class FinalExample {
final int num; {
num = 500;
}
public static void main(String args[]){
FinalExample obj = new FinalExample();
System.out.println(obj.num);
}
} 출력
500
final 메소드의 경우를 제외하고 다른 세 가지 방법으로 최종 변수를 초기화하면 곧 초기화될 것이므로 해당 클래스를 인스턴스화합니다.