static 키워드static은 자바에서 클래스 레벨에서 멤버(변수와 메서드)를 선언할 때 사용하는 키워드로, 객체의 인스턴스와 관계없이 클래스에 종속되는 멤버를 정의하는 데 사용됩니다.static의 의미static 멤버는 클래스 로드 시 메모리에 할당되며, 모든 객체가 공유합니다.static의 적용 대상class Counter {
static int count = 0; // static 변수
Counter() {
count++; // 객체가 생성될 때마다 count 증가
}
}
public class Main {
public static void main(String[] args) {
Counter c1 = new Counter();
Counter c2 = new Counter();
Counter c3 = new Counter();
System.out.println(Counter.count); // 3 출력
}
}
class MathUtil {
static int add(int a, int b) {
return a + b;
}
}
public class Main {
public static void main(String[] args) {
// static 메서드는 클래스 이름으로 호출
System.out.println(MathUtil.add(5, 10)); // 15 출력
}
}
class StaticBlockExample {
static int num;
// static 블록
static {
num = 100;
System.out.println("Static block executed.");
}
}
public class Main {
public static void main(String[] args) {
System.out.println(StaticBlockExample.num); // Static block executed. 100 출력
}
}
class OuterClass {
static class StaticNestedClass {
void display() {
System.out.println("Static Nested Class");
}
}
}
public class Main {
public static void main(String[] args) {
// Static Nested Class의 인스턴스 생성
OuterClass.StaticNestedClass nested = new OuterClass.StaticNestedClass();
nested.display(); // Static Nested Class 출력
}
}
static 메서드 내에서 인스턴스 멤버 접근 금지:
class Example {
int instanceVar = 10;
static void staticMethod() {
// System.out.println(instanceVar); // 컴파일 에러
}
}
this와 super 사용 불가:
this나 super 키워드를 사용할 수 없습니다.static 메서드는 클래스 레벨에서 호출되므로 오버라이딩되지 않습니다.
다형성은 인스턴스 메서드에서만 적용됩니다.
class Parent {
static void display() {
System.out.println("Parent static method");
}
}
class Child extends Parent {
static void display() {
System.out.println("Child static method");
}
}
public class Main {
public static void main(String[] args) {
Parent obj = new Child();
obj.display(); // Parent static method 출력
}
}
Parent obj = new Child();로 선언했지만, static 메서드는 참조 변수의 타입에 따라 호출됩니다.유틸리티 클래스:
int max = Math.max(10, 20); // Math 클래스의 static 메서드 호출
상수 정의:
static final 키워드로 상수를 정의.class Constants {
static final double PI = 3.14159;
}
System.out.println(Constants.PI); // 3.14159
공유 데이터:
class SharedData {
static int count = 0;
}
static은 클래스 레벨에서 멤버를 정의하며, 객체를 생성하지 않고도 사용 가능한 편리한 기능입니다.| 항목 | 특징 |
|---|---|
| static 변수 | 모든 객체가 공유, 클래스 로딩 시 초기화. 예: Teller.genNum. |
| static 메서드 | 객체 생성 없이 호출 가능, 인스턴스 멤버에 접근 불가. 예: Utility.printWelcomeMessage(). |
| static 블록 | 클래스 로딩 시 실행, 초기화 작업에 유용. 예: 번호표 준비 메시지 출력. |