static 을 썼을 때와 쓰지 않았을 때를 비교하면 static 의 역할을 파악하기 쉽다.
1. static 안 쓴 경우 → 객체마다 따로 존재
class Counter {
int count = 0; // 인스턴스 변수 (static 아님)
void increase() {
count++;
}
}
public class Main {
public static void main(String[] args) {
Counter a = new Counter();
Counter b = new Counter();
a.increase(); // a.count = 1
b.increase(); // b.count = 1 (a랑 b는 서로 독립적)
System.out.println(a.count); // 1
System.out.println(b.count); // 1
}
}
- 객체 a, b 각각 자기만의 count를 가짐.
- 즉, 객체마다 따로따로 공간이 만들어짐.
2. static 쓴 경우 → 모든 객체가 공유
class Counter {
static int count = 0; // 클래스 변수 (모든 객체가 공유)
void increase() {
count++;
}
}
public class Main {
public static void main(String[] args) {
Counter a = new Counter();
Counter b = new Counter();
a.increase(); // count = 1
b.increase(); // count = 2 (같은 변수 공유)
System.out.println(a.count); // 2
System.out.println(b.count); // 2
System.out.println(Counter.count); // 2 (객체 없이도 접근 가능)
}
}
- a와 b는 같은 count 변수를 공유.
- 객체를 만들지 않고 Counter.count로 바로 접근 가능.
차이 정리
구분 static 없음 (인스턴스) static 있음 (클래스)
| 메모리 위치 | 객체 안에 따로 저장 | 클래스 영역에 단 하나만 저장 |
| 객체마다 값 다름? | 다름 | 모두 공유 |
| 접근 방식 | obj.count | obj.count 또는 ClassName.count |
| 생성 시점 | 객체 new 할 때마다 생성 | 프로그램 시작 시 클래스 로딩 시점에 생성 |
그래서 static을 언제 쓰냐?
- 공통 값이 필요할 때 (예: PI, MAX_VALUE)
- 객체를 만들 필요 없는 기능 (예: Math.abs())
'JAVA' 카테고리의 다른 글
| JDK, JRE ,JVM (0) | 2025.08.28 |
|---|---|
| JAR 와 WAR 의 차이 (0) | 2025.08.28 |
| JVM GC 옵션 정리 – Garbage Collection 이해하기 (2) | 2025.08.18 |
| 5 (0) | 2025.08.18 |
| 3 (0) | 2025.08.18 |