Java 執行順序

來源:互聯網
上載者:User

標籤:

 JAVA執行順序如下:

  1.首先載入所有類中調到的class。

  2.先載入父類,再載入子類。

  3.載入過程中,會執行靜態代碼塊。

  4.new Constructor()的時候會先執行 代碼塊{},再執行 Constuctor();

  5.靜態變數在載入過程中賦值,與靜態代碼塊是從上到下的執行順序。

所以輸出結果為:

  1.父類靜態代碼塊。

  2.子類靜態代碼塊。

  3.父類 代碼塊。

  4.父類建構函式。

  5.子類代碼塊。

  6.子類建構函式。

 

 1 package test_static; 2  3 public class Fathor { 4     public String name="fathor"; 5     public static String sex="man"; 6      7     { 8         System.out.println("this is fathor‘s 代碼塊!"); 9     }10     11     static{12         sex="male";13         System.out.println("this is fathor‘s 靜態代碼塊!");14     }15     16     public Fathor() {17         System.out.println("Fathor‘sex is :"+sex);18         System.out.println("this is Fathor‘s Constructor");19     }20 }
 1 package test_static; 2  3 public class Son extends Fathor{ 4     public String name = "son"; 5      6     public static String sex="man"; 7      8     { 9         System.out.println("this is son‘s 代碼塊!");10     }11     12     static{13         sex="male";14         System.out.println("this is son‘s 靜態代碼塊!");15     }16     17     public Son() {18         System.out.println("this is son‘s Constructor");19         System.out.println("son sex is "+sex);20     }21 }
1 package test_static;2 3 public class Test {4     public static void main(String[] args) {5         Son s = new Son();6     }7 }

 執行結果:

1 this is fathor‘s 靜態代碼塊!2 this is son‘s 靜態代碼塊!3 this is fathor‘s 代碼塊!4 Fathor‘sex is :male5 this is Fathor‘s Constructor6 this is son‘s 代碼塊!7 this is son‘s Constructor8 son sex is male

 

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.