于初始化主要包含這幾方面:static 變量 、non-static變量、構造函數、new對象建立。
1、static 變量的初始化:當pulic class 被loadin(栽入)的時候,就開始對static變量初始化了,因為static 變量的refrence是存儲在static storage(靜态存儲空間)中。此時不對non-static變量和構造函數初始化,因為還沒有對象的産生,隻是把某個型别loadin。注意對于static變量隻初始化1次,當有新的對象産生時,他并不會重新被初始化了,也就是他的refrence已經固定,但他的值是可以改變的。
2、當有對象産生時,開始對此class(型别)内的non-static變量進行初始化,然後再初始化構造函數。産生已初始化的object對象。
3、按要求順序執行其它函數。
4、對有繼承的class(型别)來說:derivedclass2、derivedclass1、baseclass;因為他們之間的繼承關系,是以要想laodin derivedclass2,必須先loadin derivedclass1,如果想laodin derivedclass1,則先loadin baseclass。也就是說,laodin 順序為:baseclass、derivedclass1、deriveclass2……,每當loadin 一個class時,則按“第一條”進行初始化(初始化該class内的static變量)。
5、對有繼承的class 當用new産生對象時,會按baseclass、derivedclass1、deriveclass2……的順序,每個class内再按“第二條”進行初始化。注意derived class 的構造函數,一定要滿足baseclss可初始化。
總體思想:static變量……non-static變量……構造函數。
thinking in java中的一段程式:
PHP 代碼:
<code><code> 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(); } ///:~ </code></code>
輸出結果為:
Bowl(1)
Bowl(2)
Table()
f(1)
Bowl(4)
Bowl(5)
Bowl(3)
Cupboard()
f(2)
Creating new Cupboard() in main
f2(1)
f3(1)