構造器無法阻止自動初始化的運行,它將在構造器被調用之前發生.
class Counter{
int i;
Counter(){i = 7;}
}
i首先會被置0,然後變成7.對於所有基本類型和對象引用,包括在定義時已經指定初值的變數,這種情況都是成立的.因此編譯器不會強制你一定要在構造器中or在使用它們之前對元素進行初始化.
初始化順序:在類的內部,變數定義的先後順序決定了初始化的順序.即使變數定義散佈於方法定義之間,它們仍舊會在任何方法(包括構造器)被調用之前得到初始化.
待用資料的初始化:情況並無不同.注意:只有在第一個對象被建立(或第一次訪問待用資料)的時候,靜態對象才會被初始化.此後,靜態對象不會再次被初始化.
初始化的順序是,先"靜態"對象(如果它們尚未因前面的對象建立過程而被初始化),而後是"非靜態"對象,再執行構造器(此時可能會牽涉到很多動作,尤其是涉及繼承的時候).
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);
}
/**//*Cupboard類執行順序:1.static成員,2.非static變數or對象執行個體化的初始化,3.其它(看運行結果可理解)*/
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();
}
Java允許將多個靜態初始化動作組織成一個特殊的"靜態塊".與其他靜態初始化動作一樣,當類被裝載時,"靜態塊"執行,且這段代碼僅執行一次.
當一個程式中用到了其他的類,類是在第一次被使用的時候才被裝載,而不是在程式啟動時就裝載程式中所有可能用到的類.
無論是執行(1)代碼訪問靜態c1對象還是(2)代碼訪問靜態c1對象,Cups的靜態初始化動作都會得到執行(標號(2)中代碼啟用一行or兩行代碼都無關緊要,因為靜態初始化動作只進行一次).
Java中也有類似文法,用來初始化每一個對象的非靜態變數(只需要將"靜態塊"前的static去掉就ok了).
class Cup...{
Cup(int marker)...{
System.out.println("Cup(" + marker + ");");
}
void f(int marker)...{
System.out.println("f(" + marker + ");");
}
}
class Cups...{
static Cup c1;
static Cup c2;
static...{
c1 = new Cup(1);
c2 = new Cup(2);
System.out.println("static code block");
}
Cups()...{
System.out.println("Cups");
}
}
class ExplicitStatic...{
public static void main(String[] args)...{
System.out.println("Inside main()");
//Cups.c1.f(99); (1)
}
//static Cups x = new Cups(); (2)
//static Cups y = new Cups();
}