이펙티브자바 책을 읽다보니 내가 static과 final을 정확히 이해하지 못하고 있다는 것을 깨달았고, 이 기회에 정리해보고자 한다.
static: (변화움직임이 없이) 고정된[고정적인]
클래스에 고정된 멤버로, 객체를 생성하지 않고 필드와 메소드를 생성할 수 있다.
class StaticExample{
// static 필드
static int field = 10;
// static 메소드
static int add(int x, int y){ return x + y; }
}
public class UseStatic {
public static void main(String[] args) {
int num1 = StaticExample.add(1, 2);
int num2 = StaticExample.field1 + 3;
}
}
변수나 메소드에 static 키워드가 붙으면 컴파일러에 의해 우선적으로 method 영역 메모리에 할당된다.
⇒ 객체가 heap 영역에 올라가기 전 호출하여 사용할 수 있다.
method영역은 GC(Garbage collector)가 관여하지 않는다.
⇒ method 영역에 할당된 데이터는 시스템이 종료될 때까지 유지된다.
그러나 static은 메모리가 할당된 채로 존재하므로 자주 썼을 때 시스템 퍼포먼스에 악영향을 주기도 한다.
Java의 메모리 구조 - http://www.tcpschool.com/java/java_array_memory
static과 GC - https://mangkyu.tistory.com/47
final: (특정 과정상) 최종적인
final 키워드는 엔티티를 한 번만 할당한다.
즉, 초기값이 저장되면 최종적인 값이 되어 수정하지 못한다.
class Restaurant{
final int open = 11;
final int close;
public Restaurant(int close) {
this.close = close;
}
}
public class UseFinal {
public static void main(String[] args) {
Restaurant mexican = new Restaurant(21);
System.out.println(mexican.open); // 11
System.out.println(mexican.close); // 21
}
}
final의 변하지 않는 특성 + static의 새로운 메모리에 할당하지 않고 공유하는 특성
멤버 상수로 지정할 때 사용한다.
각각의 객체에는 사용할 수 없고 클래스에만 포함된다.
public class UsedStaticFinal {
// 상수 선언
static final int w = 2;
static final int h = 3;
static final int size;
// 상수 초기값 선언
static {
size = w * h;
}
// 상수 사용
public static void main(String[] args) {
System.out.println("사각형의 크기" + size);
}
}
https://blog.lulab.net/programming-java/java-final-when-should-i-use-it/
https://mangkyu.tistory.com/47
https://it-mesung.tistory.com/121
https://gobae.tistory.com/3
https://develop-sense.tistory.com/entry/entry/JAVA-static-final-상수