构造器初始化顺序 – 热爱改变生活
我的GitHub GitHub |     登录
  • If you can't fly, then run; if you can't run, then walk; if you can't walk, then crawl
  • but whatever you do, you have to keep moving forward。
  • “你骗得了我有什么用,这是你自己的人生”
  • 曾有伤心之地,入梦如听 此歌

构造器初始化顺序

Thinking Java sinvader 1882℃ 0评论

测试代码:

代码来自 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);
    	}
    

  • ¥ 有帮助么?打赏一下~

    转载请注明:热爱改变生活.cn » 构造器初始化顺序


    本博客只要没有注明“转”,那么均为原创。 转载请注明链接:sumile.cn » 构造器初始化顺序

    喜欢 (1)
    发表我的评论
    取消评论
    表情

    如需邮件形式接收回复,请注册登录

    Hi,你需要填写昵称和邮箱~

    • 昵称 (必填)
    • 邮箱 (必填)
    • 网址