자바에서 static 블록은 무엇을 의미하나요?

조회수 17123회
static {
    ...
}

이런 코드를 봤는데요. 이게 뭔지 전혀모르겠고 에러도 안나고 컴파일도 잘되네요. 'static' 블록이 의미하는게 뭔가요?

1 답변

  • 좋아요

    3

    싫어요
    채택 취소하기

    저런 것을 초기화 블럭이라고 합니다.

    초기화 블럭(initialization block)

    • 클래스 초기화 블럭 : 클래스 변수의 복잡한 초기화에 사용된다. 클래스가 처음 로딩될 때 한번만 수행된다.
    • 인스턴스 초기화 블럭 : 인스턴스 변수의 복잡한 초기화에 사용된다. 인스턴스가 생성될때 마다 수행된다. (생성자보다 먼저 수행된다.)
    class InitBlock{
        static {
            /* 클래스 초기화 블럭 */
        }
    
        {   /* 인스턴스 초기화 블럭 */ }
    } 
    

    보통 이런 형태인데요.

    인스턴스 변수의 초기화는 주로 생성자를 사용하기 때문에, 인스턴스 초기화 블럭은 잘 사용되지 않는다. 대신 클래스의 모든 생성자에서 공통적으로 수행되어져야 하는 코드가 있는 경우 생성자에 넣지 않고 인스턴스 초기화 블럭에 넣어 두면 코드의 중복을 줄일 수 있어서 좋다.

    Car(){
        System.out.println("Car 인스턴스 생성");
        color="White";
        gearType="Auto";
    }
    Car(String color, String gearType){
        System.out.println("Car 인스턴스 생성");
        this.color = color;
        this.gearType=gearType;
    } 
    --------------------------------------------
    // 인스턴스 블럭
    {  System.out.println("Car인스턴스 생성");  }
    
    Car(){
       color="White";
       gearType="Auto";
    }
    Car(String Color, String gearType){
       this.color=color;
       this.gearType=gearType;
    } 
    

    이처럼 코드의 중복을 제거할 수 있습니다.

    class BlockTest{
        static {                // 클래스 초기화 블럭
            System.out.println("static { }");
        }
    
        {                       // 인스턴스 초기화 블럭
            System.out.println("{ }");
        }
    
        public BlockTest(){
            System.out.println("생성자");
        }
    
        public static void main(String args[]){
            System.out.println("BlockTest bt = new BlockTest(); ");
            BlockTest bt = new BlockTest();
    
            System.out.println("BlockTset bt2 = new BlockTest();");
            BlockTest b2 = new BlockTest();
        }
    }
    

    실행결과 :: static { } BlockTest bt = new BlockTest(); { } 생성자 BlockTset bt2 = new BlockTest(); { } 생성자

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)