티스토리 뷰

이전글에서 non-static 블록을 알아보았고 이번글에서는 static 블록을 알아보겠습니다. static 블록은 non-static 블록 즉,{}에 static만 붙여준 것입니다. static{} 이런 형태입니다. 어떻게 사용되는지 살펴보면

class StaticBlock{
	StaticBlock(){
		System.out.println("Constructor called.");
	}
	static {
		System.out.println("Static Block called.");
	}
}

public class _118 {
	public static void main(String[] args) {
		StaticBlock b1 = new StaticBlock();
		StaticBlock b2 = new StaticBlock();
	}
}

 

결과

Static Block called.
Constructor called.
Constructor called.

차이점이 느껴지시나요? non-static 블록은 객체가 생성될때마다 호출이 되었는데 static 블록은 첫 번째 인스턴스를 생성하기 바로 전에 한 번만 수행됩니다. 인스턴스를 생성할때 또한 static 한 방법으로 호출되었을때 실행됩니다.

 

class StaticBlock1{
	static String result="";
	StaticBlock1(){
		System.out.println("Constructor called.");
	}
	static {
		System.out.println("Static Block called.");
	}
}

public class _118_1 {
	public static void main(String[] args) {
		System.out.print(StaticBlock1.result);
	}
}

 

결과

Static Block called.

이런식으로 클래스변수를 접근하려고 할때 호출됩니다. 객체생성이 되지 않았으니 생성자는 호출되지 않았구요.

 

class StaticBlock1{
	static String result="";
	StaticBlock1(){
		System.out.println("Constructor called.");
	}
	static {
		System.out.println("Static Block called.");
	}
}

public class _118_1 {
	public static void main(String[] args) {
		System.out.print(StaticBlock1.result);
		System.out.print(StaticBlock1.result);
	}
}

 

결과

Static Block called.

여러번 호출해도 static{} 블록은 최초 1번만 실행됩니다.

'ocjap를 위한 자바 기초 > 7 클래스와 객체' 카테고리의 다른 글

자바 {} non-static 블록  (0) 2020.05.31
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함