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();
{ }
생성자