/*
*初始化全過程:
*
*1, 第一次創建MyClass類的對象,或者第一次訪問MyClass的static方法或字段時,Java解釋器會搜尋classpath,找到MyClass.class。
*2, 裝載MyClass.class后,會對所有的static數據進行初始化。這樣第一個裝載Class對象的時候,會先進行static成員的初始化。
*3, 使用new MyClass()創建新對象的時候,MyClass對象的構建進程會先在堆里為對象分配足夠的內存。 *
*4, 清零這塊新內存,把MyClass對象的primitive類型的成員賦上缺省值。
*5, 執行定義成員數據時所作的初始化。
*6, 執行構造函數。
*/
import static net.mindview.util.Print.*;
public class Beetle extends Insect
{
private int k = printInit("Beetle.k initialized");
public Beetle()
{
print("k = " + k);
print("j = " + j);
}
private static int x2 = printInit("static Beetle.x2 initialized");
public static void main(String[] args)
{
print("Beetle constructor");
Beetle b = new Beetle();
}
}
class Insect
{
private int i = 9;
protected int j;
Insect()
{
print("i = " + i + ", j = " + j);
j = 39;
}
private static int x1 = printInit("static Insect.x1 initialized");
static int printInit(String s)
{
print(s);
return 47;
}
}
/* Output:
static Insect.x1 initialized
static Beetle.x2 initialized
Beetle constructor
i = 9, j = 0
Beetle.k initialized
k = 47
j = 39
*///:~
/****************************************************/
// 變量初始化先后順序的示例
import static net.mindview.util.Print.*;
//當創建Window的實例對象時會有消息提示
class Window
{
Window(int marker)
{
print("Window(" + marker + ")");
}
}
class House
{
Window w1 = new Window(1); // 構造函數前的變量
House()
{
//構造函數里面的變量
print("House()");
w3 = new Window(33); // 重新賦值w3
}
Window w2 = new Window(2); // 構造函數后的變量
void f()
{
print("f()");
}
Window w3 = new Window(3); // 結束類體時的對象
}
public class OrderOfInitialization
{
public static void main(String[] args)
{
House h = new House();
h.f();
}
}
/*
* 輸出結果: Window(1) Window(2) Window(3) House() Window(33) f()
*
* 從結果看出,雖然域變量w2,w3排在構造函數后面,但它的輸出卻在構造函數前面
*/
/****************************************************/
// 數組的初始化
import java.util.*;
public class ArrayInit
{
public static void main(String[] args)
{
//直接賦值方式,局限在于數組在大小編譯確定
Integer[] a = {
new Integer(1),
new Integer(2),
3, // 自動包裝
};
//new方式,適于參數數量未知的場合,或者參數類型未知的場合
Integer[] b = new Integer[] {
new Integer(1),
new Integer(2),
3, // 自動包裝
};
System.out.println(Arrays.toString(a));
System.out.println(Arrays.toString(b));
}
}
/* 輸出結果:
[1, 2, 3]
[1, 2, 3]
*///:~
Author: orangelizq
email: orangelizq@163.com
posted on 2008-12-25 11:30
桔子汁 閱讀(360)
評論(0) 編輯 收藏 所屬分類:
J2SE