劍指offer-Java類載入過程

來源:互聯網
上載者:User

標籤:

Java 類載入過程:(以A.class為例)

1. 定位A.class類,並調用findLoaderClass(string)判斷這個類是否已經存在

2. 先執行父類中static成員變數與static方法塊

3. 再執行子類中static成員變數與static方法塊

4. 接著執行父類中非static成員變數、非static方法塊和建構函式

5. 最後執行子類中非static成員變數、非static方法塊和建構函式

注意:建構函式是最後執行的。

下面用測試過的代碼輸入來說明:

(1)類中沒有成員變數時

 1 public class Test1 {     2     static{ 3         System.out.println(5); 4     } 5      6     public Test1() { 7         System.out.println(6); 8     } 9     {10         System.out.println(7);11     }12 }13 14 public class Test extends Test1 {    15     static{16         System.out.println(1);17     }18     {19         System.out.println(2);20     }    21     public Test() {22         System.out.println(3);23     }24     {25         System.out.println(4);26     }    27     public static void main(String[] args) {28         Test test=new Test();29     }30 }

輸出:5 1 7 6 2 4 3

(2)有其他執行個體化對象時

 1 public class Test1 {     2     static Test2 test22=new Test2("static_father_test2"); 3     Test2 test2=new Test2("father_test2");     4     static{ 5         System.out.println(5); 6     } 7      8     public Test1() { 9         System.out.println(6);10     }11     {12         System.out.println(7);13     }14 }15 16 public class Test2 {17     public Test2(String str) {18         System.out.println("test2:"+str);19     }20 }21 public class Test extends Test1 {    22     static Test2 test22=new Test2("static_test22");    23     Test2 test2=new Test2("test2");    24     static{25         System.out.println(1);26     }27     {28         System.out.println(2);29     }30     31     public Test() {32         System.out.println(3);33     }34     {35         System.out.println(4);36     }    37     public static void main(String[] args) {38         Test test=new Test();39     }40 }

輸出列印:
test2:static_father_test2
5
test2:static_test22
1
test2:father_test2
7
6
test2:test2
2
4
3

 

劍指offer-Java類載入過程

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.