首先看一个例子,以这个例子引导。
public class Test {
public A(int id) {
System.out.println("Test(" + id + ")");
}
}
class Demo {
//静态块
static {
System.out.println("This is static block!");
}
//非静态块
{
System.out.println("This is non-static block!");
}
Test t1 = new Test(1); //------------------1--------------------
public Demo() {
System.out.println("This is Demo's constructor!");
Test t2 = new Test(2);
}
Test t3 = new Test(3);
public static void main(String[] args) {
Demo dm = new Demo();
}
}
输出:
This is static block!
This is non-static block!
Test(1)
Test(3)
This is Demo's constructor!
Test(2)
由此看出:
1、先装载.class文件,创建Class对象,对静态数据(由static声明的)进行初始化,而且只进行一次初始化。
2、new Demo()在堆上进行空间分配。
3、执行非静态块。
4、执行所有方法外定义的变量初始化。
5、执行构造方法。
在上例中,若在注释1行前面加上static关键字,输出就为变为:
This is static block!
Test(1)
This is non-static block!
Test(3)
This is Demo's constructor!
Test(2)
由此看出静态数据时在装载的时候执行的,且只执行一次。总体来说,执行顺序为:静态块,静态属性(装载时)->非静态块,属性->构造方法。
指出:对于静态块和静态属性或非静态块和静态属性的执行顺序决定于它们在代码中的顺序。