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();
  }
}
问号处,不是java中内部类实例化需要绑定外部类的实例吗?

解决方案 »

  1.   


    但你的程序没有体现出来 
    public static void main(String[] args) {
    Egg2 e2 = new BigEgg2();
    e2.g();

    //new Yolk();//error  error
    //No enclosing instance of type BigEgg2 is accessible. 
    //Must qualify the allocation with an enclosing instance of type BigEgg2 
    //(e.g. x.new A() where x is an instance of BigEgg2).
        
    System.out.println("------------");
    e2.new Yolk();//correct

        }
      

  2.   

    因为在外部类中实例化内部类是不用写那个所谓的    外部类.内部类。
    因为比如class A{
        private int a;
        public fun(){
            this.a和a是一个意思。
        }
    }所以你this.内部类就是内部类直接实例化,一样的。
      

  3.   

    这是在外部类中能看到这个内部类,所有可以这么定义。
    因为在外面定义外部这个类时,不就有一个外部类的this对象指向了这个内部类实例。。
    还有就是如果在外部要定义一个内部类对象的话 就得先定义他的外部类
      

  4.   


     private Yolk y = this.new Yolk();
      

  5.   


    是在外部类的非static方法或者非static变量定义时才不用那样写吧?
      

  6.   

    偶明白了,问号处是在定义一个非static成员变量,所以就有一个隐形的this存在,因此可直接那样写,谢谢各位!