Java

Java) static 키워드의 이해와 활용 예제

pogun 2025. 1. 9. 19:19

static 키워드란?

: static은 정적을 의미하며, 클래스 로딩 시 메모리에 올라가며 프로그램이 종료될 때까지 존재한다.

 

특징 :

    공유 : 클래스의 모든 객체가 동일한 static 변수와 메서드를 공유한다.

    인스턴스 생성 없이 접근 가능 : 클래스 이름으로 직접 호출할 수 있다.

static 메서드 접근 방법

public class MainClass {
    public static void main(String[] args) {
    	MyClass.staticNumber = 10; // 객체 생성 없이 사용 가능
        MyClass.static_method();
    }
}

class MyClass{
    int number;
    public static int staticNumber; 
    
    public void method(){                  // instance method

    }
    
    public static void static_method(){    // 독립적된 녀석 class method
        // number == 11;
        // method();
        // this.method(); 3개 다 접근 불가

        System.out.println("MyClass static_method()");
    }
}

: 객체 생성 없이 바로 접근 가능

출력 값 : "MyClass static_method()"

: static 메서드가 실행될 때는 클래스 로더가 메모리에 static 메서드를 올려 실행한다.

: 하지만, 인스턴스 변수와 인스턴스 메서드는 특정 객체가 생성된 이후에야 사용할 수 있다.

: 따라서, static 메서드 내에서 객체에 속한 멤버(인스턴스 변수 및 메서드)를 참조할 수 없다.

초기 값 : 0 

public class MainClass {
    public static void main(String[] args) {
    	MyClass cls = new MyClass();
        System.out.println("number : " + cls.number); // 멤버변수 초기값 0
        System.out.println(MyClass.staticNumber);  // static변수 초기값 0
    }
}

객체 생성 후 인스턴스 변수와 static 변수 비교

public class MainClass {
    public static void main(String[] args) {
    	MyClass cls = new MyClass();
        System.out.println(cls.number);
        cls.number++;

        MyClass my = new MyClass();
        System.out.println(cls.number);
    }
}

: number는 인스턴스 변수로, 객체마다 독립적인 값을 가진다.

: 각 객체는 number 값을 따로 관리

: cls.number++;을 해도 my 객체 number에는 영향이 없다.

결과 값 : 0, 0

public class MainClass {
    public static void main(String[] args) {
    	System.out.println(MyClass.staticNumber); // static 변수
        MyClass.staticNumber++;
        System.out.println(MyClass.staticNumber); // 모든 객체가 공유하는 값
    }
}

: staticNumber는 클래스 변수로, 모든 객체가 값을 공유한다.

결과 값 : 0, 1

정적 메서드를 통한 객체 생성

public class MainClass {
    public static void main(String[] args) {
    	
        BaseClass bc = BaseClass.getInstance();
    }
}

class BaseClass{
    int number;
    String name;

    public BaseClass(){

    }
    public void methodOne(){

    }
    public void methodTwo(){

    }
    public static BaseClass getInstance(){
        BaseClass bc = new BaseClass();
        bc.methodOne();
        bc.methodTwo();
        return bc;
    }
}

: BaseClass.getInstance() 메서드를 호출하여 BaseClass 객체를 생성하고, 그 객체를 변수 bc에 저장

: 이 메서드는 BaseClass 클래스 내에서 정의된 정적 메서드(static method)로, 객체를 생성하는 역할을 한다.

 

 public static BaseClass getInstance(){} : 

: static으로 선언된 메서드로, 클래스 이름으로 호출할 수 있다.(BaseClass 객체를 생성하고 반환)

: getInstance() 메서드는 BaseClass 객체를 생성하고, 생성된 객체에서 methodOne()과 Two()를 호출한 후, 생성된 객체를 반환