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();
t2.f2(1);
t3.f3(1);
}
static Table t2 = new Table();
static Cupboard t3 = new Cupboard();
}[/code]作者: bruinchen 时间: 2011-11-12 00:30 本帖最后由 bruinchen 于 2011-11-12 00:31 编辑
Bowl1
Bowl2
Table()
f1
Bowl4
Bowl5
Cupboard()
f2
Creating new Cupboard in main
Cupboard()
f2
Creating new Cupboard in main
Cupboard()
f2
f21
f31
和答案有点差距,
我推断错误的原因是:知道加载类时,加载静态成员,而忽视了在加载静态类时,在类里有引用其他对象会先把其他对象调用运行,在运行自己的构造方法,作者: 吉许 时间: 2011-11-12 11:09
Bowl(1)
Bowl(2)
Table()
f(1)
Bowl(4)
Bowl(5)
Bowl(3)
Cupboard()
f(2)
Creating new Cupboard() in main
Bowl(4)
Bowl(5)
Bowl(3)
Cupboard()
f(2)
Creating new Cupboard() in main
Bowl(4)
Bowl(5)
Bowl(3)
Cupboard()
f(2)
f2(1)
f3(1)
我的答案也不对,以前看过这方面的知识点,但又忘了被静态修饰时只在类被加裁时执行一次,只后不会再被执行。
如果在能混合进重载和继承就更为经典了.我就借这个发个构造函数重载的,大家也分析下:
class Cake{
Cake(){System.out.println("Cake()");}
}
class Meal {
Meal() { System.out.println("Meal()"); }
}
class Bread {
Bread() { System.out.println("Bread()"); }
}
class Cheese {
Cheese() { System.out.println("Cheese()"); }
}
class Lettuce {
Lettuce() { System.out.println("Lettuce()"); }
}
class Lunch extends Meal {
Lunch() { System.out.println("Lunch()"); }
}