class Egg2
{
protected class Yolk
{
public Yolk()//第2步,第7步
{
System.out.println("Egg2.Yolk()");
}
public void f()
{
System.out.println("Egg2.Yolk.f()");
}
}
private Yolk y = new Yolk();//第1步, 加载类时将非静态变量加载
public Egg2()//第3步,调用构造函数
{
System.out.println("New Egg2()");
}
public void insertYolk(Yolk yy)//第6步
{
y = yy;
}
public void go()
{
y.f();
}
}
class BigEgg2 extends Egg2
{
public class Yolk extends Egg2.Yolk
{
public Yolk()//第8步
{
System.out.println("BigEgg2.Yolk()");
}
public void f()
{
System.out.println("BigEgg2.Yolk.f()");
}
}
public BigEgg2()//第4步,调用构造函数
{
insertYolk(new Yolk());//第5步
}
public static void main(String[] args)
{
Egg2 e2 = new BigEgg2();
e2.go();//y此时指向BigEgg2对象(在第5步中已确定BigEggy的引用向上转型为Egg2),所以调用的是BigEgg2中的f()
}
}