类初试话的先后循序:
父类静态块和域->子类静态块和域->父类实例域和块->父类构造器 ->子类实例域和块->子类构造器
package staticinit.one;
public class ClassInitOrder {
public static void main(String[] args) {
new Son();
/*
* Father staticVal print()...
* Father staticBlock print()...
* Son staticVal print()...
* Son staticBlock print()...
* Father instanceVal print()...
* Father instanceBlock print()...
* Father constructor...
* Son instanceVal print()...
* Son instanceBlock print()...
* Son constructor...
*/
}
}
class Father {
private static String staticVal = print("staticVal");
private String instanceVal = print("instanceVal");
{
print("instanceBlock");
}
static {
print("staticBlock");
}
public Father() {
System.out.println("Father constructor...");
}
public static String print(String name) {
System.out.println("Father " + name + " print()...");
return null;
}
}
class Son extends Father {
private static String staticVal = print("staticVal");
private String instanceVal = print("instanceVal");
{
print("instanceBlock");
}
static {
print("staticBlock");
}
public Son() {
System.out.println("Son constructor...");
}
public static String print(String name) {
System.out.println("Son " + name + " print()...");
return null;
}
}
注:域和块的初始化先后顺序取决于其在类中的位置先后。(类的域、块与类的方法有何区别,为何域和块会自动被初始化,而方法不会被初始化?)