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