转自:http://my.oschina.net/u/998081/blog/177882
类A的定义
01 | package com.sequence.test; |
02 |
03 | public class A { |
04 | |
05 | // 静态变量 |
06 | static String name; |
07 | |
08 | // 静态自由块 |
09 | static { |
10 | name = "a" ; |
11 | System.out.println( "static filed of A inited." ); |
12 | } |
13 | // 实例变量 |
14 | String type; |
15 | // 非静态自由块 |
16 | { |
17 | type = "a.type" ; |
18 | System.out.println( "no-static filed of A inited." ); |
19 | } |
20 | String size; |
21 | // 构造函数 |
22 | public A(){ |
23 | size = "a.size" ; |
24 | System.out.println( "construct func of A inited." ); |
25 | } |
26 | } |
01 | package com.sequence.test; |
02 |
03 | public class B extends A{ |
04 | |
05 | // 静态自由块 |
06 | static { |
07 | System.out.println( "static filed of B inited." ); |
08 | } |
09 | // 非静态自由块 |
10 | { |
11 | System.out.println( "no-static filed of B inited." ); |
12 | } |
13 | public B(){ |
14 | System.out.println( "constuct func of B inited." ); |
15 | } |
16 | } |
01 | package com.sequence.test; |
02 |
03 | public class InitSequenceTest { |
04 |
05 | /** |
06 | * @param args |
07 | */ |
08 | public static void main(String[] args) { |
09 | // TODO Auto-generated method stub |
10 | new B(); |
11 | } |
12 |
13 | } |
输出:
总结如下:1,静态自由块在class加载的时候执行。只会执行一次。
2,非静态自由块在新建类的实例的时候执行。可以多次执行。在新建其或子类的实例时,就会执行。
当存在多个同一种类型的自由块时,执行的顺序是根据他们在代码块中出现的顺序。
3,当子类继承父类,执行的顺序如下:父类的静态变量和静态域->子类的静态变量和静态域->父类的非静态自由块->父类的构造函数->子类的非静态自由块->子类的构造函数