해당 데이터의 메모리 할당을 컴파일 시간에 하는 것을 의미
1) static 변수
메모리 공간에 하나만 존재하며, 어디서나 접근 가능한 변수
static 변수의 초기화 시점은 JVM(Java Virtual Machine)에 의해서 클래스가 메모리 공간에 올라가는 순간임
static 변수 사용이유 : 인스턴트간에 데이터 공유가 필요한 상황에 사용
static final 변수 : 클래스 내부 또는 외부에 참조용도로만 사용하는 변수 ( ex. static final double PI = 3.14)
2) static 메소드 : 인스턴스를 사용하지 않아도 static 메소드 호출 가능
class Parents {
public static void show() {
System.out.println("show");
}
}
public class Application {
public static void main(String[] args) {
Parents.show();
}
}
classCounter{
static int count = 0;
Counter() {
count++; // count는 더이상 객체변수가 아니므로 this를 제거하는 것이 좋다.System.out.println(count); // this 제거}
}
publicclassSample{
publicstaticvoidmain(String[] args) {
Counter c1 = newCounter();
Counter c2 = newCounter();
}
}
int count = 0 앞에 static 키워드를 붙였더니 count 값이 공유되어 다음과 같이 count가 증가되어 출력된다.
1
2