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

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

static 語句的執行時機實在第一次加載類信息的時候(如調用類的靜態方法,訪問靜態成員,或者調用構造函數), static 語句和 static 成員變量的初始化會先於其餘語句執行,並且只會在加載類信息的時候執行一次,之後再訪問該類或new新對象都不會執行函數

而非 static 語句或成員變量,其執行順序在static語句執行以後,而在構造方法執行以前,總的來講他們的順序以下this

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

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

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

4. 父類的構造方法對象

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

6. 子類的構造方法class

參見以下例子變量

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語句塊和成員變量的初始化,最後再執行構造方法的內容

相關文章
相關標籤/搜索