[Java] static

Leejaegun·2025년 4월 15일

java

목록 보기
1/1

✅ Java static 정리 요약표

항목설명
정의static은 클래스에 소속된 공통 멤버(변수/메서드)를 의미
목적객체 없이도 사용 가능, 메모리 절약, 공용 자원 공유
메모리프로그램 시작 시 한 번만 메모리 할당됨 (클래스 로딩 시점)
접근 방식클래스명.멤버명 으로 접근
(같은 클래스 내부면 생략 가능)
사용 위치변수, 메서드, 블록, 클래스(중첩 클래스) 앞에 사용 가능

🧪 1. static 변수 (클래스 변수)

public class Counter {
    static int count = 0;  // 모든 객체가 공유함

    public Counter() {
        count++;
    }
}

사용

System.out.println(Counter.count);  // 객체 없이도 접근 가능

⚙ 2. static 메서드 (클래스 메서드)

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

사용

MathUtil.square(5);  // 클래스명으로 호출

static 메서드 안에서는 this 사용 불가,
일반 인스턴스 변수도 사용할 수 없음 ❌


🧱 3. static 블록 (클래스 초기화용)

public class App {
    static {
        System.out.println("클래스 로딩 시 딱 한 번 실행됨!");
    }
}

🧳 4. static 중첩 클래스 (클래스 안 클래스)

class Outer {
    static class Inner {
        static void hello() {
            System.out.println("Hello from static inner!");
        }
    }
}

사용

Outer.Inner.hello();  // 외부 객체 필요 없음

❗ static 관련 주의사항

상황설명
객체 없이 접근✅ 클래스명.멤버명 으로 가능
다른 클래스에서 접근✅ public static이면 가능
static 메서드 안에서 인스턴스 변수 사용❌ 불가능
static 변수는 여러 객체가 공유✅ 모든 객체가 같은 변수 참조
static은 객체와 무관하게 존재✅ 클래스 자체의 속성

🎯 최종 요약

static = 공용 + 클래스 단위 + 객체 없이 사용 가능

static은 언제 쓰나?
모든 객체가 공유해야 하는 값 (예: 카운터, 설정)
도구성 메서드 (예: Math.abs, Integer.parseInt)
프로그램 실행 전 초기화 로직 (static 블록)
profile
Lee_AA

0개의 댓글