测试代码:
代码来自 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)
总结
在对一个类进行实例化的时候:
Cupboard() { ShiLiHuaShunXu.print("Cupboard()"); bowl4.f1(2); }
)