Ryuzy 2025. 5. 19. 23:16
728x90
반응형

1. static

static은 자바에서 클래스에 속하는 멤버(변수나 메서드)를 정의할 때 사용하는 키워드입니다. static으로 선언된 변수나 메서드는 객체를 생성하지 않고도 클래스 이름으로 직접 접근할 수 있으며, 모든 객체가 공유하는 공통된 데이터로 사용됩니다. 예를 들어, static int count는 생성된 모든 객체가 같은 count 값을 공유하게 되며, static 메서드는 인스턴스 변수에 접근할 수 없고 this 키워드도 사용할 수 없습니다. 주로 유틸리티 함수나 공통 속성을 정의할 때 사용됩니다.

 

1. static 변수(정적 변수)

모든 객체가 공유하는 변수입니다. 보통 객체 수 카운트 등에 사용됩니다.

class Car {
    static int count = 0;  // 클래스 변수 (공용)

    public Car() {
        count++;  // 객체가 생성될 때마다 count 증가
    }
}

public class Main {
    public static void main(String[] args) {
        new Car();
        new Car();
        new Car();
        System.out.println("총 생성된 자동차 수: " + Car.count);  // 출력: 3
    }
}

 

2. static 메서드 (정적 메서드)

객체를 생성하지 않고 사용할 수 있는 클래스 메서드입니다. 대표적인 예는 Math 클래스입니다.

class Calculator {
    public static int add(int a, int b) {
        return a + b;
    }
}

public class Main {
    public static void main(String[] args) {
        int result = Calculator.add(5, 3);  // 객체 생성 없이 사용
        System.out.println("결과: " + result);  // 출력: 8
    }
}

 

3. static 블록

클래스가 처음 로딩될 때 딱 한 번 실행되는 초기화 블록입니다. 복잡한 static 변수 초기화에 사용됩니다.

  • 클래스가 JVM에 의해 처음 로딩될 때 자동으로 실행됩니다.
  • 주로 static 변수의 복잡한 초기화에 사용됩니다.
  • 생성자보다 먼저, 단 한 번만 실행됩니다.
  • static initializer 안에서는 인스턴스 변수나 메서드 사용 불가합니다.
class Config {
    static int maxUsers;

    static {
        // 복잡한 초기화 코드
        maxUsers = 100;
        System.out.println("Config 클래스가 로딩되면서 초기화됨!");
    }
}

public class Main {
    public static void main(String[] args) {
        System.out.println("최대 사용자 수: " + Config.maxUsers);
    }
}

 

class ServerConfig {
    static int port;
    static String mode;

    static {
        System.out.println("static initializer 실행됨");
        port = 8080;
        mode = "production";
    }
}

public class Main {
    public static void main(String[] args) {
        System.out.println("포트: " + ServerConfig.port);
        System.out.println("모드: " + ServerConfig.mode);
    }
}

 

4. static import

static import를 사용하면 클래스명을 생략하고 static 멤버를 직접 쓸 수 있습니다.

import static java.lang.Math.*;

public class Main {
    public static void main(String[] args) {
        System.out.println(sqrt(16));  // Math.sqrt(16) → sqrt만 사용 가능
        System.out.println(pow(2, 3)); // Math.pow(2, 3)
    }
}

 

 

2. 싱글톤(Singleton) 패턴이란?

하나의 클래스에 대해 오직 하나의 인스턴스만 생성되도록 보장하는 디자인 패턴입니다.

  • 공통된 설정, 리소스, 서비스 등을 한 객체로 공유하고 싶을 때 사용
  • 예: 설정 클래스, 로깅, DB 연결 관리자 등
class Singleton {
    // 1. 클래스 내부에서 static으로 단 하나의 인스턴스 생성
    private static final Singleton instance = new Singleton();

    // 2. 생성자는 private으로 외부에서 생성 못 하게 막음
    private Singleton() {
        System.out.println("싱글톤 객체 생성됨");
    }

    // 3. 외부에서 instance에 접근할 수 있는 static 메서드 제공
    public static Singleton getInstance() {
        return instance;
    }

    // 예시 기능
    public void printMessage() {
        System.out.println("싱글톤 패턴으로 실행 중입니다!");
    }
}

 

public class Main {
    public static void main(String[] args) {
        Singleton s1 = Singleton.getInstance();
        Singleton s2 = Singleton.getInstance();

        s1.printMessage();

        System.out.println(s1 == s2); // true → 같은 객체
    }
}

 

 

728x90
반응형