java2019. 9. 12. 18:16

 

 

static 블록은 객체가 생성되거나, 클래스 참조가 발생하는 경우 한번 호출 된다.

(static 메소드 또는 static변수 참조)

 

초기화 블럭(initialization block)


1, 클래스 초기화 블럭 : 클래스 변수의 복잡한 초기화에 사용된다. 클래스가 처음 로딩될 때 한번만 수행된다.
2,  인스턴스 초기화 블럭 : 인스턴스 변수의 복잡한 초기화에 사용된다. 인스턴스가 생성될때 마다 수행된다.

 ( 생성자보다 먼저 수행된다. )

인스턴스 변수의 초기화는 주로 생성자를 사용하기 때문에, 인스턴스 초기화 블럭은 잘 사용되지 않는다. 

 대신 클래스의 모든 생성자에서 공통적으로 수행되어져야 하는 코드가 있는 경우 생성자에 넣지 않고 인스턴스 초기화 블럭에 넣어 두면 코드의 중복을 줄일 수 있어서 좋다.
class InitBlock{
    static {
        /* 클래스 초기화 블럭 */
    }

    {   /* 인스턴스 초기화 블럭 */ }

 

 

클래스 내에서만 선언 가능.

 

딱히 분리할 이유는 없지만 아래와 같이 분리된 경우, 선언된 순서로 호출되므로 주의.


import static java.lang.System.out;

public class TestApplication {
	
	
	public static void main(String [] args) {
			
		Human h1 = new Human();
		Human h2 = new Human();
		
	}

}


class Human {

	static int count=98127391;//임의의 값으로 초기화
	static {
		System.out.println("static block called 111");
		count=0;//0으로 초기화
		Hello();
		
	}
	static {
		System.out.println("static block called 222");
		count=0;//0으로 초기화
		Hello();
		
	}
	public Human(){
		count ++;
		System.out.println("human : "+count);	
	}
	
	
	private static void Hello() {
		System.out.println("hello!!!");
	}
}

	

출처 : 자바의 신

Posted by easy16