Java 靜態(static)與非靜態執行順序
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 shoutingnormal 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語句塊和成員變數的初始化,最後再執行構造方法的內容