在實際的工做過程當中,幾乎從沒用過JAVA的代碼塊。不過既然作了這方面的學習與測試,就索性記錄下來防止忘記。同一個招式,聖鬥士是不會學習第二遍的... java
首先,上代碼: 函數
public class CodeBlockTest { public CodeBlockTest(){ //構造函數代碼塊 System.out.println("this is construct!"); { System.out.println("this is construct code block!"); } } //靜態代碼塊 static{ System.out.println("this is static code block!"); } //普通代碼塊 { System.out.println("this is code block!"); } @SuppressWarnings("unused") public static void main(String[] args){ { System.out.println("你會不會突然的出現..?"); } CodeBlockTest cbt = null; { System.out.println("在街角的咖啡店..?"); } cbt = new CodeBlockTest(); } }
直接右鍵運行,測試結果以下: 學習
this is static code block!
你會不會突然的出現..?
在街角的咖啡店..?
this is code block!
this is construct!
this is construct code block! 測試
從輸出的結果來看,靜態代碼塊應該是在類加載的時候就開始執行,普通代碼塊則在類實例化以後第一時間執行,以後是構造函數,構造函數代碼塊。。。 this
接下來引入子類: spa
public class SonCodeBlockTest extends CodeBlockTest{ public SonCodeBlockTest(){ System.out.println("This is son construct!"); } static{ System.out.println("This is son static block!"); } @SuppressWarnings("unused") public static void main(String[] args){ SonCodeBlockTest son = new SonCodeBlockTest(); } }
this is static code block!
This is son static block!
this is code block!
this is construct!
this is construct code block!
This is son construct! code
很明顯,因爲類的加載順序,執行順序是:父類的靜態代碼塊-->子類的靜態代碼塊-->父類的普通代碼塊-->父類的構造函數-->子類的普通代碼塊(若是有的話)-->子類的構造函數 class