[JAVA] static

현서황·2024년 9월 20일

JAVA

목록 보기
13/16

static 변수

static으로 선언된 변수는 클래스 자체에 속하며, 해당 클래스의 모든 인스턴스가 동일한 값을 공유한다. 인스턴스 변수와 달리, 클래스 로드 시점에 메모리에 한 번만 생성된다.

class Counter {
    public static int count = 0;  // static 변수

    public Counter() {
        count++;
    }
}

public class Main {
    public static void main(String[] args) {
        Counter c1 = new Counter();
        Counter c2 = new Counter();
        System.out.println(Counter.count);  // 출력: 2
    }
}

count변수는 static으로 선언되었으므로, Counter 클래스의 모든 인스턴스에서 공통적으로 사용된다.
두 개의 인스턴스를 생성하더라도 각 인스턴스마다 별도로 존재하는 것이 아니라, 하나의 count 값이 공유된다!


static 메서드

static 메서드는 인스턴스가 아니라 클래스에 속하는 메서드이다. 따라서 인스턴스를 생성하지 않고도 호출할 수 있다.
static 메서드는 static 변수 또는 다른 static 메서드에만 직접 접근할 수 있으며, 인스턴스 변수나 메서드에는 직접 접근할 수 없다.

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

public class Main {
    public static void main(String[] args) {
        int result = MathUtils.add(5, 3);  // 인스턴스 없이 클래스 이름으로 호출
        System.out.println(result);  // 출력: 8
    }
}

static 블록

static 블록은 클래스가 로드될 때 한 번만 실행되는 코드 블록이다. 클래스가 처음 메모리에 로드될 때 초기화 작업을 수행하기 위해 사용된다.

class Example {
    public static int value;

    static {
        value = 10;
        System.out.println("Static block executed");
    }
}

public class Main {
    public static void main(String[] args) {
        System.out.println(Example.value);  // 출력: Static block executed, 10
    }
}

위 코드에서 static 블록은 Example클래스가 메모리에 로드될 때 자동으로 실행된다. 그 후, value가 초기화되고 static 블록의 내용이 실행된다.


static 클래스

static키워드는 내부 클래스에도 사용할 수 있다. static으로 선언된 내부 클래스는 외부 클래스의 인스턴스에 종속되지 않고, 클래스 자체에 속하게 된다.

class OuterClass {
    static class InnerClass {
        public void display() {
            System.out.println("This is a static inner class");
        }
    }
}

public class Main {
    public static void main(String[] args) {
        OuterClass.InnerClass inner = new OuterClass.InnerClass();
        inner.display();  // 출력: This is a static inner class
    }
}

InnerClass는 static으로 선언된 내부 클래스이다. 외부 클래스인 OuterClass의 인스턴스를 생성하지 않고도, InnerClass의 인스턴스를 생성할 수 있다.


Static의 장점

  • 메모리 절약 : static 변수는 클래스당 한 번만 생성되므로, 인스턴스마다 생성되지 않아 메모리 사용을 줄일 수 있다.
  • 전역 상태 관리 : static 변수는 클래스 전체에서 공통된 상태를 유지할 때 유용하다.
  • 인스턴스 생성 없이 접근 가능 : static 메서드와 변수는 인스턴스를 생성하지 않고 클래스 이름으로 직접 접근할 수 있다.
profile
노는 게 제일 좋은 뽀로로

0개의 댓글