看如下程序:
1 class A { 2 static{ 3 System.out.println("A static"); 4 } 5 6 { 7 System.out.println("A not static"); 8 } 9 10 public A(){ 11 System.out.println("A new"); 12 } 13 } 14 15 class B extends A{ 16 static{ 17 System.out.println("B static"); 18 } 19 20 { 21 System.out.println("B not static"); 22 } 23 24 public B(){ 25 System.out.println("B new"); 26 } 27 } 28 29 public class MainTest { 30 public static void main(String[] args) { 31 A ab= new B(); 32 ab= new B(); 33 } 34 }
輸出如下:
A static
B static
A not static
A new
B not static
B new
A not static
A new
B not static
B new
結論:
靜態代碼塊只有類首次加載進內存時調用一次,只此一次。
非靜態代碼塊,每次創建對象時,會在構造函數之前被調用。
構造函數,每次創建對象時,最后調用。
創建子類對象時,先創建父類對象,再創建子類對象。