java初始化順序
在一個類里,初始化的順序是由變量在類內的定義順序決定的。即使變量定義大量遍布于方法定義的中間,那些變量仍會在調用任何方法之前得到初始化——甚至在構建器調用之前。例如:class Tag {
Tag(int marker) {
System.out.println("Tag(" + marker + ")");
}
}
class Card {
Tag t1 = new Tag(1); // 先初始化t1
Card() {
// Indicate we're in the constructor:
System.out.println("Card()");
t3 = new Tag(33); // Re-initialize t3
}
Tag t2 = new Tag(2); // 然后初始化t2
void f() {
System.out.println("f()");
}
Tag t3 = new Tag(3); // 接著初始化t3
}
public class OrderOfInitialization {
public static void main(String[] args) {
Card t = new Card();
t.f(); // Shows that construction is done
}
}
它的輸入結果如下:
"Tag(1)",
"Tag(2)",
"Tag(3)",
"Card()",
"Tag(33)",
"f()"
// 以下是人綜合例子:
//總的原則:先靜態后動態,先定義初始化,后構造函數初始化
/**
* 實例化Child對象時
* 先父類靜態成員初始化,后子類靜態成員初始化
* 然后是父類成員,父類構造函數,最后是子類
* 成員,子類構造函數*/
class Parent {
private static int s = getS("父類靜態成員");private int num = getNum();
public Parent() {
System.out.println("父類構造函數");
}private static int getS(String string) {
System.out.println(string);
return 47;
}public int getNum() {
System.out.println("父類私有成員");
return num;
}public static void setS(int s) {
Parent.s = s;
}}
class Child extends Parent {
private int num = prt("子類私有成員");private static int s = getS("子類靜態成員");
public static void setS(int s) {
Child.s = s;
}public Child() {
System.out.println("子類構造函數");
}public void setNum(int num) {
this.num = num;
}private int prt(String string) {
System.out.println(string);
return 5;
}public static int getS(String string) {
System.out.println(string);
return s;
}
}
public class Tee {/**
* @param args
*/
public static void main(String[] args) {
Child c = new Child();
c.setNum(100);// 為什么輸出的是0
System.out.print(c.getNum());// Child cStatic = new Child();
// cStatic.setS(100);
// System.out.println(cStatic.getS("s"));
}}
最后輸出結果:
父類靜態成員
子類靜態成員
父類私有成員
父類構造函數
子類私有成員
子類構造函數
父類私有成員
0