当前位置: 技术问答>java相关
谁能真正的理解这个程序运行过程,请讲讲?
来源: 互联网 发布时间:2015-02-17
本文导语: 程序: class Egg2{ protected class Yolk{ public Yolk(){ System.out.println("Egg2.Yolk()"); } public void f(){ System.out.println("5"); System.out.println("Egg2.Yolk.f()"); } } private Yolk y=new Yolk(); publi...
程序:
class Egg2{
protected class Yolk{
public Yolk(){
System.out.println("Egg2.Yolk()");
}
public void f(){
System.out.println("5");
System.out.println("Egg2.Yolk.f()");
}
}
private Yolk y=new Yolk();
public Egg2(){
System.out.println("2");
System.out.println("New Egg2()");
System.out.println("3");
}
public void insertYolk(Yolk yy){
System.out.println("*");
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();
System.out.println("4");
e2.g();
}
}
结果:
---------- run ----------
Egg2.Yolk()
New Egg2()
Egg2.Yolk()
BigEgg2.Yolk()
BigEgg2.Yolk().f()
Normal Termination
Output completed (0 sec consumed).
class Egg2{
protected class Yolk{
public Yolk(){
System.out.println("Egg2.Yolk()");
}
public void f(){
System.out.println("5");
System.out.println("Egg2.Yolk.f()");
}
}
private Yolk y=new Yolk();
public Egg2(){
System.out.println("2");
System.out.println("New Egg2()");
System.out.println("3");
}
public void insertYolk(Yolk yy){
System.out.println("*");
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();
System.out.println("4");
e2.g();
}
}
结果:
---------- run ----------
Egg2.Yolk()
New Egg2()
Egg2.Yolk()
BigEgg2.Yolk()
BigEgg2.Yolk().f()
Normal Termination
Output completed (0 sec consumed).
|
当BigEgg2运行时,首先找到Egg2,因为BigEgg2是extends Egg2,假如Egg2还有基类,也会被载入的,
,接着会在基类执行static(如果有)初始化,
此时必要的类已经载入,所以能够创建对象,
然后调用基类构建器
,接着会在基类执行static(如果有)初始化,
此时必要的类已经载入,所以能够创建对象,
然后调用基类构建器