상수를 선언할 때
private final로 선언하면 되는데
굳이 private static final 선언하는 이유가 뭘까
결론부터 말하자면 초기화 한 값을 끝까지 유지하기 위해서이다. (값을 불변으로 만들기 위해)
만약 private final 로 선언한다면 직접적으로 값을 참조할 수 없지만 생성자를 통해 값을 참조할 수 있다.
하지만 private static final 로 선언한다면 생성자를 통해 값을 참조할 수 없다.
(이때 private static final 변수는 반드시 초기화되어 있어야 한다.)
절대 해당 값을 바꾸지 않겠다는 표현과 유사하다.
private static final 을 선언한 변수를 사용하면 재할당하지 못하며,
메모리가 한번 올라가면 같은 값을 클래스 내부의 전체 필드, 메서드에서 공유한다.
private final 을 선언한 변수를 사용하면 재할당하지 못하며,
해당 필드, 메서드 별로 호출할 때마다 새롭게 값을 할당(인스턴스화)한다.
그렇다면 상수로 사용하려고 할 때, 그 값은 변하지 않을 것인데 호출할 때마다 새롭게 인스턴스화할 필요가 없다.
한번 메모리에 올려두고 계속 같은 값을 가져다 쓰면 된다.
public class StaticFinalExample {
private final int var;
public StaticFinalExample(int var) {
this.var = var;
}
}
private static은 메모리에 올라가므로 초기화를 반드시 해주어야 한다.
public class StaticFinalExample {
private static final int var;
public StaticFinalExample(int var) {
this.var = var;
}
}
따라서 위의 코드는 컴파일 오류가 발생함을 확인할 수 있다.
참조 : (JAVA) private final 과 private static final (tistory.com)