
static은 클래스 멤버(변수나 메서드)를 정의할 때 사용되는 키워드로, 해당 멤버가 클래스 수준에서 공유되도록 합니다. 즉, static 멤버는 객체 인스턴스에 종속되지 않고 클래스 자체에 속합니다. 이를 통해 메모리 사용을 효율적으로 관리하고, 공통된 값을 여러 인스턴스에서 공유할 수 있습니다.
public class StaticExample {
static int sharedCounter = 0;
public static void incrementCounter() {
sharedCounter++;
}
}
public class StaticExample {
static int counter = 0;
public static void printCounter() {
System.out.println("Counter: " + counter);
}
}
public class StaticBlockExample {
static int sharedValue;
static {
sharedValue = 42;
System.out.println("Static block executed");
}
}
다음 예제는 static 키워드의 실제 활용을 보여줍니다.
public class StaticExample {
static int counter = 0; // 모든 인스턴스가 공유하는 변수
public StaticExample() {
counter++;
}
public static void printCounter() { // static 메서드
System.out.println("현재 생성된 객체 수: " + counter);
}
public static void main(String[] args) {
new StaticExample();
new StaticExample();
StaticExample.printCounter(); // 출력: 현재 생성된 객체 수: 2
}
}