바이오닉크로니클 2024. 12. 10. 23:42

 

Java의 static 키워드는 클래스, 메서드, 변수 또는 블록에 적용되어 클래스 수준에서 동작하도록 만든다. 이를 통해 객체 인스턴스와 독립적으로 사용할 수 있는 요소를 정의할 수 있다.

static의 주요 특징
1. 클래스 수준에서 동작
static으로 선언된 요소는 클래스에 속하며, 객체를 생성하지 않고도 접근할 수 있다.
반대로 static이 없는 요소는 인스턴스와 연결되며, 객체를 생성해야만 접근할 수 있다.

2. 공유된 메모리
static 요소는 클래스당 하나만 생성되며 모든 객체(인스턴스)가 이를 공유한다.
클래스가 메모리에 로드될 때 한 번만 생성되며, 프로그램이 종료될 때까지 유지된다.
모든 객체는 같은 클래스에서 생성된 모든 인스턴스를 가리킨다. 모든 객체가 공유하는 건 같은 클래스의 모든 인스턴스가 동일한 static 변수를 참조한단 것이다.
객체마다 별도로 메모리를 할당하지 않으며, 모든 객체가 하나의 메모리 공간을 참조한다.

이는 특정 클래스에서 생성된 인스턴스에 국한된다. 다른 클래스에서 생성된 객체는 모든 객체에 포함되지 않는다.

 

class A {  
    static int shared = 0;  
}  
  
class B {  
    static int shared = 0;  
}  
  
public class static_예시 {  
    public static void main(String[] args) {  
        A.shared++;  
        B.shared++;  
  
        System.out.println("A의 shared: " + A.shared); // 출력: 1  
        System.out.println("B의 shared: " + B.shared); // 출력: 1  
    }  
}
출력결과

A의 shared: 1
B의 shared: 1

 

A 클래스와 B 클래스의 shared 변수는 서로 독립적이다.
모든 객체가 공유한다는 표현은 같은 클래스 내에서만 적용된다.

 

public class Example {
    static int sharedValue = 0; // static 변수 (클래스 공유)
    int instanceValue = 0; // 인스턴스 변수 (객체별로 독립적)

    public void increment() {
        sharedValue++; // 모든 객체가 공유
        instanceValue++; // 각 객체별로 독립적
    }
}

public class Main {
    public static void main(String[] args) {
        Example obj1 = new Example(); // 첫 번째 객체
        Example obj2 = new Example(); // 두 번째 객체

        obj1.increment(); // obj1의 메서드 호출
        obj2.increment(); // obj2의 메서드 호출

        System.out.println("obj1 instanceValue: " + obj1.instanceValue); // 1
        System.out.println("obj2 instanceValue: " + obj2.instanceValue); // 1
        System.out.println("sharedValue: " + Example.sharedValue); // 2
    }
}

 

static 변수 sharedValue는 obj1과 obj2가 공유하여 2번 증가하기에 값은 2이다.
instanceValue는 각 객체(obj1, obj2)가 독립적으로 관리하여 값은 1이다.

3. this 사용 불가
static 메서드는 객체에 속하지 않으므로 객체 참조를 나타내는 this 키워드를 사용할 수 없다.