当前位置: 技术问答>java相关
简单的java程序问题,请求回答!!!!
来源: 互联网 发布时间:2015-02-28
本文导语: class Egg2 { protected class Yolk { public Yolk() { System.out.println("Egg2.Yolk()"); } public void f() { System.out.println("Egg2.Yolk.f()"); } } private Yolk y=new Yolk(); public Egg2() { ...
class Egg2 {
protected class Yolk {
public Yolk() {
System.out.println("Egg2.Yolk()");
}
public void f() {
System.out.println("Egg2.Yolk.f()");
}
}
private Yolk y=new Yolk();
public Egg2() {
System.out.println("new Egg2()");
}
public void insertYolk(Yolk yy) { y=yy; }
public void g() { y.f(); }
}
public class BigEgg2 extends Egg2 {
public class Yolk extends Egg2.Yolk {
public Yolk() {
System.out.println("BigEgg2.Yolk()");
}
public void f() {
System.out.println("BigEgg2.Yolk().f()");
}
}
public BigEgg2() { insertYolk(new Yolk()); }
public static void main(String[] args) {
Egg2 e2=new BigEgg2();
e2.g();
}
}///:~
输出:
Egg2.Yolk()
new Egg2()
Egg2.Yolk()
BigEgg2.Yolk()
BigEgg2.Yolk().f()
请问:在这个程序里,为什么在基类Egg2中,先初始化内部类Yolk,后初始化Egg2,而在派生类BigEgg2中却是先调用BigEgg2,然后才调用Yolk的??还是我对这个程序理解错了?想问问这个程序调用各函数的过程是什么?谢谢!!
protected class Yolk {
public Yolk() {
System.out.println("Egg2.Yolk()");
}
public void f() {
System.out.println("Egg2.Yolk.f()");
}
}
private Yolk y=new Yolk();
public Egg2() {
System.out.println("new Egg2()");
}
public void insertYolk(Yolk yy) { y=yy; }
public void g() { y.f(); }
}
public class BigEgg2 extends Egg2 {
public class Yolk extends Egg2.Yolk {
public Yolk() {
System.out.println("BigEgg2.Yolk()");
}
public void f() {
System.out.println("BigEgg2.Yolk().f()");
}
}
public BigEgg2() { insertYolk(new Yolk()); }
public static void main(String[] args) {
Egg2 e2=new BigEgg2();
e2.g();
}
}///:~
输出:
Egg2.Yolk()
new Egg2()
Egg2.Yolk()
BigEgg2.Yolk()
BigEgg2.Yolk().f()
请问:在这个程序里,为什么在基类Egg2中,先初始化内部类Yolk,后初始化Egg2,而在派生类BigEgg2中却是先调用BigEgg2,然后才调用Yolk的??还是我对这个程序理解错了?想问问这个程序调用各函数的过程是什么?谢谢!!
|
因为初始的时候并不是先执行构建器里的。。。而是Yolk y=new Yolk();