构造器初始化顺序

无简介

测试代码:

代码来自Thinking Java文中的代码

class Bowl {
Bowl(int marker) {
ShiLiHuaShunXu.print(“Bowl(” + marker + “)”);
}

void f1(int marker) {
ShiLiHuaShunXu.print(“f1(” + marker + “)”);
}
}

class Table {
static Bowl bowl1 = new Bowl(1);

Table() {
ShiLiHuaShunXu.print(“Table()”);
bowl2.f1(1);
}

void f2(int marker) {
ShiLiHuaShunXu.print(“f2(” + marker + “)”);
}

static Bowl bowl2 = new Bowl(2);
}

class Cupboard {
Bowl bowl3 = new Bowl(3);
static Bowl bowl4 = new Bowl(4);

Cupboard() {
ShiLiHuaShunXu.print(“Cupboard()”);
bowl4.f1(2);
}

void f3(int marker) {
ShiLiHuaShunXu.print(“f3(” + marker + “)”);
}

static Bowl bowl5 = new Bowl(5);
}

public class ShiLiHuaShunXu {
public static void main(String[] args) {
print(“Creating new Cupboard() in main”);
new Cupboard();
print(“Creating new Cupboard() in main”);
new Cupboard();
table.f2(1);
cupboard.f3(1);
}

static Table table = new Table();
static Cupboard cupboard = new Cupboard();
public static void print(String str){
System.out.println(str);
}
}

运行结果:

Bowl(1) Bowl(2) Table() f1(1) Bowl(4) Bowl(5) Bowl(3) Cupboard() f1(2) Creating new Cupboard() in main Bowl(3) Cupboard() f1(2) Creating new Cupboard() in main Bowl(3) Cupboard() f1(2) f2(1) f3(1)

总结

在对一个类进行实例化的时候:* 1:如果内部有static,首先要对static进行初始化(如:static Table table = new Table();),且只初始化一次。

  • 2:如果内部有非static的,在对static初始化之后,对非static进行初始化(如:Bowl bowl3 = new Bowl(3)😉,每一次对这个类进行实例化,这个非static的都会被初始化。

  • 3:这些初始化完成之后,才会调用构造方法(如:

    Cupboard() {
    ShiLiHuaShunXu.print(“Cupboard()”);
    bowl4.f1(2);
    }

-------------本文结束  感谢您的阅读-------------
下次一定