public class TestLab {
static Test aStatic=new Test();
public static void main(String[] args) {
TestLab obj=new TestLab();
}
static{
System.out.println("In static block of TestLab");
}
}
public class Test {
static Test ref=new Test();
Test()
{
System.out.println("Default Constructor of Test");
}
static
{
System.out.println("In Static Block of Test");
}
{
System.out.println("In instance block of Test");
}
}
通常静态块在类加载期间首先执行。执行上述示例时,会收到以下输出:
在测试的实例块中
测试的默认构造函数
在静态测试块中
在测试的实例块中
测试的默认构造函数
在 TestLab 的静态块中
为什么测试类的实例块和默认构造函数在测试类的静态块之前执行?