Java 靜態(static)與非靜態語句執行順序

來源:互聯網
上載者:User

Java中的靜態(static)關鍵字只能用於成員變數或語句塊,不能用於局部變數

static 語句的執行時機實在第一次載入類資訊的時候(如調用類的靜態方法,訪問靜態成員,或者調用建構函式), static 語句和 static 成員變數的初始化會先於其他語句執行,而且只會在載入類資訊的時候執行一次,以後再訪問該類或new新對象都不會執行

而非 static 語句或成員變數,其執行順序在static語句執行之後,而在構造方法執行之前,總的來說他們的順序如下

1. 父類的 static 語句和 static 成員變數

2. 子類的 static 語句和 static 成員變數

3. 父類的 非 static 語句塊和 非 static 成員變數

4. 父類的構造方法

5. 子類的 非 static 語句塊和 非 static 成員變數

6. 子類的構造方法

參見如下例子

Bell.java

public class Bell {    public Bell(int i) {        System.out.println("bell " + i + ": ding ling ding ling...");    }}

Dog.java

public class Dog {    // static statement    static String name = "Bill";    static {        System.out.println("static statement executed");    }    static Bell bell = new Bell(1);    // normal statement    {        System.out.println("normal statement executed");    }    Bell bell2 = new Bell(2);    static void shout() {        System.out.println("a dog is shouting");    }    public Dog() {        System.out.println("a new dog created");    }}

Test.java

public class Test {    public static void main(String[] args) {        // static int a = 1; this statement will lead to error        System.out.println(Dog.name);        Dog.shout();    // static statement would execute when Dog.class info loaded        System.out.println();        new Dog();  // normal statement would execute when construct method invoked        new Dog();    }}

 

程式輸出:

static statement executed
bell 1: ding ling ding ling...
Bill
a dog is shouting

normal statement executed
bell 2: ding ling ding ling...
a new dog created
normal statement executed
bell 2: ding ling ding ling...
a new dog created

可見第一次訪問Dog類的static成員變數name時,static語句塊和成員變數都會初始化一次,並且在以後調用static方法shout()或構造方法時,static語句塊及成員變數不會再次被載入

而調用new Dog()構造方法時,先執非static語句塊和成員變數的初始化,最後再執行構造方法的內容

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.