ocjap를 위한 자바 기초/7 클래스와 객체
자바 static {} 블록
xemaker
2020. 5. 31. 08:50
이전글에서 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번만 실행됩니다.