아래 코드를 고려하면 예외를 throw하지 않고 실행됩니다.클래스가로드되기 전에 new 연산자를 사용할 수있는 이유는 무엇입니까?
public class Test1 {
public static int k = 0;
public static Test1 t1 = new Test1("t1");
public static Test1 t2 = new Test1("t2");
public static int i = print("i");
public static int n = 99;
public int j = print("j");
{
print("constructor block");
}
static {
print("static block");
}
public Test1(String str) {
System.out.println((++k) + ":" + str + " i=" + i + " n=" + n);
++i;
++n;
}
public static int print(String str) {
System.out.println((++k) + ":" + str + " i=" + i + " n=" + n);
++n;
return ++i;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Test1 t = new Test1("init");
}
}
출력 : I 디버거로 단계별
1:j i=0 n=0
2:constructor block i=1 n=1
3:t1 i=2 n=2
4:j i=3 n=3
5:constructor block i=4 n=4
6:t2 i=5 n=5
7:i i=6 n=6
8:static block i=7 n=99
9:j i=8 n=100
10:constructor block i=9 n=101
11:init i=10 n=102
. 은 clinit 메소드가 init 메소드를 호출하는 것을 볼 수 있습니다. clinit 메서드는 여전히 클래스 로딩의 일부이므로 Test1 클래스가 준비되기 전에 Test1 개체를 인스턴스화 할 수 있습니까?
클래스 (즉, 정적 변수)는 클래스를 처음 사용할 때만 초기화해야합니까? –
나는 i, n, x, z 등을 더 추가해야한다고 생각한다. 더 많은 다른 장소에 인쇄 방법을 붙여 넣고 임의의 반환 값을 추가한다. – FazoM
@Fazovsky 그건별로 도움이되지 않는 코멘트입니다. – Thomas