[Java] static이란

우노구나·2025년 7월 25일

자바에서 static정적(static) 멤버를 정의할 때 사용하는 키워드로,
클래스에 속하지만 객체(instance)에는 속하지 않음을 의미합니다.

  • 인스턴스를 생성하지 않아도 클래스명으로 직접 접근 가능.

  • 클래스 로더가 클래스를 메모리에 올릴 때 단 한 번만 메모리에 할당됨.

  • 모든 인스턴스가 공유하는 값을 가질 수 있음.


static 변수

class Counter {
    static int count = 0;  // 모든 인스턴스가 공유
    int num;

    Counter() {
        count++;
        num = count;
    }
}

public class Test {
    public static void main(String[] args) {
        Counter c1 = new Counter();
        Counter c2 = new Counter();
        System.out.println(Counter.count); // 2
        System.out.println(c1.num);        // 1
        System.out.println(c2.num);        // 2
    }
}
  • Counter.count는 모든 객체가 공유하는 변수.

  • num은 객체마다 다른 값.


static 메소드

  • 인스턴스 생성 없이 호출 가능.

  • 객체와 관련 없는 기능(유틸성 기능)에 적합.

  • 인스턴스 변수나 메서드에 접근 불가 (왜냐하면 객체가 없어도 호출되니까).

class MathUtil {
    static int square(int x) {
        return x * x;
    }
}

public class Test {
    public static void main(String[] args) {
        int result = MathUtil.square(5); // 인스턴스 생성 없이 사용
        System.out.println(result);      // 25
    }
}

static 블록

class Example {
    static int value;
    static {
        value = 10;
        System.out.println("static 블록 실행!");
    }
}
  • Example 클래스가 처음 로딩될 때 단 한 번 실행됨.

참고

static은 JVM의 Method Area에 저장되어 공유된다.

profile
기술 블로그

0개의 댓글