class X
{
Y b=new Y();
X()
{
System.out.print("X");
}
}
class Y
{
Y()
{
System.out.print("Y");
}
}
public class Z extends X
{
Z()
{
System.out.print("Z");
}
Y y=new Y();
public static void main(String[] args)
{
new Z();
}
}
------解决方案--------------------
class X {
X() {
this.b = new Y();//2
System.out.print("X");//4
}
Y b;
}
class Y {
Y() {
System.out.print("Y");//3,6
}
}
public class Z extends X {
Z() {
this.y = new Y();//5
System.out.print("Z");//7
}
public static void main(String[] args) {
Z z = new Z();//1
}
Y y;
}
注释中的数字代表执行顺序,输出如下:
YXYZ
1)程序的入口点main方法被调用,通过new生成了z对象
2)调用父类的构造方法时,通过new生成了b对象
3)调用Y类的构造方法时,打印了字母Y出来
4)顺次调用,打印了字母X出来
5)调用子类的构造方法,通过new生成了y对象
6)再次调用Y类的构造方法时,打印了字母Y出来
7)顺次调用,打印了字母Z出来