(轉) Java 靜態代碼塊和非靜態代碼塊

來源:互聯網
上載者:User

標籤:lis   虛擬機器   順序   lan   static   his   extends   main   依次   

參考:http://uule.iteye.com/blog/1558891

Java中的靜態代碼塊是在虛擬機器載入類的時候,就執行的,而且只執行一次。如果static代碼塊有多個,JVM將按照它們在類中出現的先後順序依次執行它們,每個代碼塊只會被執行一次。

非靜態代碼塊是在類new一個執行個體的時候執行,而且是每次new對象執行個體都會執行。

代碼的執行順序
  1. 主調類的靜態代碼塊
  2. 對象父類的靜態代碼塊
  3. 對象的靜態代碼塊
  4. 對象父類的非靜態代碼塊
  5. 對象父類的建構函式
  6. 對象的非靜態代碼塊
  7. 對象的建構函式
範例程式碼
public class StaticBlockTest1 {    //主調類的非靜態代碼塊    {        System.out.println("StaticBlockTest1 not static block"); } //主調類的靜態代碼塊 static { System.out.println("StaticBlockTest1 static block"); } public StaticBlockTest1(){ System.out.println("constructor StaticBlockTest1"); } public static void main(String[] args) { Children children = new Children(); children.getValue(); }}class Parent{ private String name; private int age; //父類無參構造方法 public Parent(){ System.out.println("Parent constructor method"); { System.out.println("Parent constructor method--> not static block"); } } //父類的非靜態代碼塊 { System.out.println("Parent not static block"); name = "zhangsan"; age = 50; } //父類靜態代碼塊 static { System.out.println("Parent static block"); } //父類有參構造方法 public Parent(String name, int age) { System.out.println("Parent constructor method"); this.name = "lishi"; this.age = 51; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; }}class Children extends Parent{ //子類靜態代碼塊 static { System.out.println("Children static block"); } //子類非靜態代碼塊 { System.out.println("Children not static block"); } //子類無參構造方法 public Children(){ System.out.println("Children constructor method"); } public void getValue(){ //this.setName("lisi"); //this.setAge(51); System.out.println(this.getName() + this.getAge()); }}

 

輸出結果

StaticBlockTest1 static block   //主調類的靜態代碼塊Parent static block //父類的靜態代碼塊Children static block //子類的靜態代碼塊Parent not static block //父類的非靜態代碼塊Parent constructor method //父類的建構函式Parent constructor method--> not static blockChildren not static block //主調類的非靜態代碼塊Children constructor method //主調類的建構函式zhangsan50 //主調main方法
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

總結:

  1. 按照前面提到的順序執行
  2. 子類定義無參構造方法,調用的父類也是無參構造方法

(轉) 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.