一、在类的内部,变量定义的先后顺序军定了初始化的顺序。及时变量定义散布于方法定义之间,它们仍会在任何方法,包括构造方法,被调用前得到初始化。
public class Tree {
public static void main(String[] args) {
House h = new House();//调用
h.f();
}
}
class Window {
public Window(int mark) {
System.out.println("Window(" + mark + ")");
}
}
class House {
Window w1 = new Window(1);//1
public House() {//4
System.out.println("House()");
w3 = new Window(33);
}
Window w2 = new Window(2);//2
void f() {//5
System.out.println("f()");
}
Window w3 = new Window(3); //3
}
/* Output:
Window(1)
Window(2)
Window(3)
House()
Window(33)
f()
*/
二、一个类的初始化过程(包涵静态)
创建一个Dog类
1、当首次创建一个Dog的对象时(构造器实际上也是静态方法),或者调用Dog类里的静态方法/静态域首次被访问时,Java解释器必须查找类路径,以定位Dog.class文件。
2、然后载入Dog.class,有关静态初始化的所有动作都是执行。所以,静态初始化只会在Class对象首次加载的时候进行一次。
3、当用new Dog()创建对象时,首先将在堆上为Dog对象分配租后的存储空间。
4、这块存储空间会被清零,这就自动地将Dog对象中的所有进本类型数据都设置成了默认值,而引用则被设置成了null。
5、执行所有出现于字段定义处的初始化动作。
6、执行构造器。
class Bowl {
public Bowl(int marker) {
System.out.println("Bowl(" + marker +")");
}
void f1(int marker) {
System.out.println("f1(" + marker +")");
}
}
class Table {//1
static Bowl bowl1 = new Bowl(1);//1.1
public Table() {
System.out.println("Table()");//1.3
bowl2.f1(1);//1.4
}
void f2(int marker) {//8
System.out.println("f2(" + marker + ")");
}
static Bowl bowl2 = new Bowl(2);//1.2
}
class Cupboard {//2
Bowl bowl3 = new Bowl(3);//2.3 //5.1 //7.1
static Bowl bowl4 = new Bowl(4);//2.1
public Cupboard() {
System.out.println("Cupboard()");//2.4 //5.2 //7.2
bowl4.f1(2);//2.5 //5.3 //7.3
}
void f3(int marker) {//9
System.out.println("f3(" + marker + ")");
}
static Bowl bowl5 = new Bowl(5);//2.2
}
public class StaticInit {
public static void main(String[] args) {//3
System.out.println("Creating Cupboard");//4
new Cupboard();//5
System.out.println("Creating Cupboard");//6
new Cupboard();//7
table.f2(1);//8
cupboard.f3(1);//9
}
static Table table = new Table();//1
static Cupboard cupboard = new Cupboard();//2
}
/* Output
Bowl(1)
Bowl(2)
Table()
f1(1)
Bowl(4)
Bowl(5)
Bowl(3)
Cupboard()
f1(2)
Creating Cupboard
Bowl(3)
Cupboard()
f1(2)
Creating Cupboard
Bowl(3)
Cupboard()
f1(2)
f2(1)
f3(1)
*/
三、基本类型初始化值
public class Flower {
boolean t;
char c;
byte b;
short s;
int i;
long l;
float f;
double d;
Flower flower;
void printInit() {
System.out.println("boolean = " + t);
System.out.println("char = [" + c +"]");
System.out.println("byte = " + b);
System.out.println("short = " + s);
System.out.println("int = " + i);
System.out.println("long = " + l);
System.out.println("float = " + f);
System.out.println("double = " + d);
System.out.println("Flower = " + f);
}
public static void main(String[] args) {
Flower flower = new Flower();
flower.printInit();
}
}
/* Output
boolean = false
char = [ ]
byte = 0
short = 0
int = 0
long = 0
float = 0.0
double = 0.0
Flower = null
*/
《Java编程思想》