{
public static void main(String[] args){
B ba = new B();
System.out.println("-------------------------------");
B bb = new B();
}
};
class Target
{
public Target(String s){
System.out.println("Target("+s+")");
}
};
class A
{
public static Target td = new Target("static in A");
static{
System.out.println("static block in A");
}
{
System.out.println("non-static block in A");
}
public Target ta = new Target("in A");
};
class B extends A
{
public Target tb = new Target("in B");
static{
System.out.println("static block in B");
}
static public Target tc = new Target("static in B");
{
System.out.println("non-static block in B");
}
};
结果:
static block in A
static block in B
Target(static in B)
non-static block in A
Target(in A)
Target(in B)
non-static block in B
-------------------------------
non-static block in A
Target(in A)
Target(in B)
non-static block in B
注意:
-
All data fields are initialized to their default value (0, false, or null).
-
All field initializers and initialization blocks are executed, in the order in which they occur in the class declaration.
-
If the first line of the constructor calls a second constructor, then the body of the second constructor is executed.
-
The body of the constructor is executed。
另外,可以看到:
先父类的static,后子类的static,然后父类的非static,再子类的非static。
static包括静态的字段和初始化块。
非static包括非静态字段和初始化块。
同级别的字段或初始化块的顺序就依赖于定义的先后了。
还有一点简单的,顺便提一下:
static的东东只在类装入的时候,执行一次。不是每次实例化一个对象时都执行。
顺便提第二点:在jdk5中因为支持可变参数列表所以,
是成立的。
另外,关于初始化问题参见:
http://www.javaworld.com/javaworld/jw-03-1998/jw-03-initialization.html?page=1