Static vs Instance Initializer Block

Static Initializer Block

  • class 로딩 시 호출
  • instance variable이나 method에 접근 못함
  • static variable 초기화에 사용
public class StaticIntializerBlockTest {
    private static int id = 5;
    static {
        if (id <10) id = 20;
        else id = 100;
    }

    public static int getId() {
        return id;
    }

    public static void print() {
        System.out.println("StaticIntializerBlockTest.id=" + getId());
    }
}

public class StaticInstanceInitializerBlockTest {

    public static void main(String[] args) {
        StaticIntializerBlockTest.print();
    }
}

StaticIntializerBlockTest.id=20 // static block 이 호출되면서 20으로 셋팅

Instance Initializer Block

  • 객체 생성시 호출
  • super 생성자 이후에 실행하고, 생성자보다 먼저 실행
  • instance variable이나 method에 접근 가능
  • 모든 생성자의 공통 부분을 instance initializer block에 넣어줌
class InstanceInitializerBlockSuper {
    public InstanceInitializerBlockSuper() {
        System.out.println("InstanceInitializerBlockSuper");
    }
}

public class InstanceInitializerBlockTest extends InstanceInitializerBlockSuper {
    private int id = 5;
    {
        if (id <10) id = 20;
        else id = 100;
    }

    public InstanceInitializerBlockTest() {
        System.out.println("InstanceInitializerBlockTest.id=" + this.id);
    }

    public InstanceInitializerBlockTest(int id) {
        System.out.println(“InstanceInitializerBlockTest.id=" + this.id);
        this.id = id;
    }

    public int getId() {
        return id;
    }

    public void print() {
        System.out.println("StaticIntializerBlockTest.id=" + getId());
    }
}

public class StaticInstanceInitializerBlockTest {
    public static void main(String[] args) {
        InstanceInitializerBlockTest i = new InstanceInitializerBlockTest();
        i.print();
        i = new InstanceInitializerBlockTest(30);
        i.print();
    }
}

InstanceInitializerBlockSuper // super 생성자 이후에 실행
InstanceInitializerBlockTest.id=20 // instance block 호출되면서 20으로 셋팅 
id=20
InstanceInitializerBlockSuper // super 생성자 이후에 실행
InstanceInitializerBlockTest.id=20 // instance block 호출되면서 20으로 셋팅된후 this.id = id를 통해서 30으로 셋팅
id=30

https://stackoverflow.com/questions/12550135/static-block-vs-initializer-block-in-java