초기화 블럭(initialization block)

seringee·2023년 4월 23일
0

개발자개인공부

목록 보기
1/28
  • 클래스 초기화 블럭 : 클래스 변수의 복잡한 초기화에 사용된다. 클래스가 처음 로딩될 때 한번만 수행된다.
  • 인스턴스 초기화 블럭 : 인스턴스 변수의 복잡한 초기화에 사용된다. 인스턴스가 생성될때 마다 수행된다. (생성자보다 먼저 수행된다.)
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();
{ }
생성자

profile
개발 공부 정리하고 저장하기

0개의 댓글