
⚠️ 이 글은 저작권 이슈로 인해 일부 내용이 수정 또는 제거되었습니다.
static 키워드란?| 구분 | 선언 위치 | 메모리 할당 시점 | 접근 방법 | 공유 여부 |
| 인스턴스 변수 | 클래스 내부 | 객체 생성 시 | obj.field | ❌ 개별 유지 |
클래스 변수 (static) | 클래스 내부 | 클래스 로딩 시 | ClassName.field | ✅ 모든 객체가 공유 |
public class Counter {
static int count = 0; // 클래스 변수
int id; // 인스턴스 변수
Counter() {
count++;
id = count;
}
}public class Counter {
static int count = 0; // 클래스 변수
int id; // 인스턴스 변수
Counter() {
count++;
id = count;
}
}클래스명.메서드명())public class MathUtil {
static int square(int n) {
return n * n;
}
}
int result = MathUtil.square(5); // 객체 없이 호출 가능public class MathUtil {
static int square(int n) {
return n * n;
}
}
int result = MathUtil.square(5); // 객체 없이 호출 가능static {
// static 변수 복잡 초기화 가능
}static {
// static 변수 복잡 초기화 가능
}static final), 유틸리티 클래스