class Bowl {
Bowl(int er) {
System.out.println("Bowl(" + er + ")");
}
void f1(int er) {
System.out.println("f1(" + er + ")");
}
}class Table {
static Bowl bowl1 = new Bowl(1);
Table() {
System.out.println("Table()");
bowl2.f1(1);
}
void f2(int er) {
System.out.println("f2(" + er + ")");
}
static Bowl bowl2 = new Bowl(2);
}class Cupboard {
Bowl bowl3 = new Bowl(3);
static Bowl bowl4 = new Bowl(4);
Cupboard() {
System.out.println("Cupboard()");
bowl4.f1(2);
}
void f3(int er) {
System.out.println("f3(" + er + ")");
}
static Bowl bowl5 = new Bowl(5);
}public class StaticInitialization {
public static void main(String[] args) {
System.out.println("Creating new Cupboard() in main");
new Cupboard();
System.out.println("Creating new Cupboard() in main");
new Cupboard();
table.f2(1);
cupboard.f3(1);
}
static Table table = new Table();
static Cupboard cupboard = new Cupboard();
}为什么执行到new Cupboard() 后会再执行Bowl bowl3 = new Bowl(3) 。本来以为输出Creating new Cupboard() in main后,接着是输出Cupboard()和f1(2),没想到中间插着一个Bowl(3)。
输出结果:
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)
Bowl(int er) {
System.out.println("Bowl(" + er + ")");
}
void f1(int er) {
System.out.println("f1(" + er + ")");
}
}class Table {
static Bowl bowl1 = new Bowl(1);
Table() {
System.out.println("Table()");
bowl2.f1(1);
}
void f2(int er) {
System.out.println("f2(" + er + ")");
}
static Bowl bowl2 = new Bowl(2);
}class Cupboard {
Bowl bowl3 = new Bowl(3);
static Bowl bowl4 = new Bowl(4);
Cupboard() {
System.out.println("Cupboard()");
bowl4.f1(2);
}
void f3(int er) {
System.out.println("f3(" + er + ")");
}
static Bowl bowl5 = new Bowl(5);
}public class StaticInitialization {
public static void main(String[] args) {
System.out.println("Creating new Cupboard() in main");
new Cupboard();
System.out.println("Creating new Cupboard() in main");
new Cupboard();
table.f2(1);
cupboard.f3(1);
}
static Table table = new Table();
static Cupboard cupboard = new Cupboard();
}为什么执行到new Cupboard() 后会再执行Bowl bowl3 = new Bowl(3) 。本来以为输出Creating new Cupboard() in main后,接着是输出Cupboard()和f1(2),没想到中间插着一个Bowl(3)。
输出结果:
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)
调用new Cupboard()和cupboard.f3(1)运行机制有什么区别
详情看看Thinking in JAVA里面的第96页
Creating new Cupboard() in main
Bowl(3)
Cupboard()
f1(2)
Creating new Cupboard() in main
Bowl(3)因为你的main中 new Cupboard();产生了一个新的对象
Bowl bowl3 = new Bowl(3);这句代码必定被执行一次的嘛
也就造成了输出
Creating new Cupboard() in main
Bowl(3)
两个静态的就不执行了
输出也没问题啊
与非静态的初实化问题 后面有总结的!