public class Parent
{
private Delegete delegete = new Delegete();
static//加載時執行,只會執行一次
{
System.out.println("static block of parent!");
}
public Parent(String name)
{
System.out.println("to construct parent!");
}
{
System.out.println("comman block of parent!");
}
}
class Child extends Parent
{
static
{
System.out.println("static block of child!");
}
static//能夠包含多個靜態塊,按照次序依次執行
{
System.out.println("second static block of child!");
}
//普通代碼塊與變量的初始化等同的,按照次序依次執行
{
System.out.println("comman mode of child!");
}
private Delegete delegete = new Delegete();
{
System.out.println("second comman mode of child!");
}
//構造順序,先執行靜態塊(父類、子類順序執行)
//執行父類成員變量的初始化或普通代碼塊,而後執行構造函數
//執行子類成員變量的初始化或普通代碼塊,而後執行構造函數
public Child()
{
super("DLH");
System.out.println("to construct child!");
}
public static void main (String[] args) {
Child c = new Child();
System.out.println("**********************************");
Child c2 = new Child();
}
}
class Delegete
{
static
{
System.out.println("static of Delegete!");
}
public Delegete()
{
System.out.println("to construct delegete!");
}
}
輸出結果:
static block of parent!
static block of child!
second static block of child!
static of Delegete!
to construct delegete!
comman block of parent!
to construct parent!
comman mode of child!
to construct delegete!
second comman mode of child!
to construct child!
**********************************
to construct delegete!
comman block of parent!
to construct parent!
comman mode of child!
to construct delegete!
second comman mode of child!
to construct child!