關於static的初始化順序

於初始化主要包含這幾方面:static 變量 、non-static變量、構造函數、new對象創建。

一、static 變量的初始化:當pulic class 被loadin(栽入)的時候,就開始對static變量初始化了,由於static 變量的refrence是存儲在static storage(靜態存儲空間)中。此時不對non-static變量和構造函數初始化,由於尚未對象的產生,只是把某個型別loadin。注意對於static變量只初始化1次,當有新的對象產生時,他並不會從新被初始化了,也就是他的refrence已經固定,但他的值是能夠改變的。

二、當有對象產生時,開始對此class(型別)內的non-static變量進行初始化,而後再初始化構造函數。產生已初始化的object對象。

三、按要求順序執行其它函數。

四、對有繼承的class(型別)來講:derivedclass二、derivedclass一、baseclass;由於他們之間的繼承關係,因此要想laodin derivedclass2,必須先loadin derivedclass1,若是想laodin derivedclass1,則先loadin baseclass。也就是說,laodin 順序爲:baseclass、derivedclass一、deriveclass2……,每當loadin 一個class時,則按「第一條」進行初始化(初始化該class內的static變量)。

五、對有繼承的class 當用new產生對象時,會按baseclass、derivedclass一、deriveclass2……的順序,每一個class內再按「第二條」進行初始化。注意derived class 的構造函數,必定要知足baseclss可初始化。

整體思想:static變量……non-static變量……構造函數。



thinking in java中的一段程序:
PHP 代碼:
 
class Bowl {
 
Bowl(int marker) {
   
System.out.println("Bowl(" marker ")");
 }
 
void f(int marker) {
   
System.out.println("f(" marker ")");
 }
}
class 
Table {
 static 
Bowl b1 = new Bowl(1);
 
Table() {
   
System.out.println("Table()");
   
b2.f(1);
 }
 
void f2(int marker) {
   
System.out.println("f2(" marker ")");
 }
 static 
Bowl b2 = new Bowl(2);
}

class 
Cupboard {
 
Bowl b3 = new Bowl(3);
 static 
Bowl b4 = new Bowl(4);
 
Cupboard() {
   
System.out.println("Cupboard()");
   
b4.f(2);
 }
 
void f3(int marker) {
   
System.out.println("f3(" marker ")");
 }
 static 
Bowl b5 = new Bowl(5);
}

public class 
StaticInitialization {
 public static 
void main(String[] args) {
   
System.out.println(
     
"Creating new Cupboard() in main");
   new 
Cupboard();
   
System.out.println(
     
"Creating new Cupboard() in main");
   new 
Cupboard();
   
t2.f2(1);
   
t3.f3(1);
 }
 static 
Table t2 = new Table();
 static 
Cupboard t3 = new Cupboard();
///:~ 
輸出結果爲: Bowl(1) Bowl(2) Table() f(1) Bowl(4) Bowl(5) Bowl(3) Cupboard() f(2) Creating new Cupboard() in main Bowl(3) Cupboard() f(2) Creating new Cupboard() in main Bowl(3) Cupboard() f(2) f2(1) f3(1)
相關文章
相關標籤/搜索