上这个类

public abstract class Mother{
  public class Embryo{
    public void ecluse(){
      bear(this);
    }
  }
  abstract void bear(Embryo e);
}

我只有在拥有Mother实例的情况下才能创建Embryo实例:
new Mother(){...}.new Embryo().ecluse();

问题:
  • 如何将Mother定义为接口(interface)?
  • 最佳答案

    嵌套类Embryostatic中隐式地为interface

    因此,它无权访问实际上可调用的方法bear,该方法与Mother接口(interface)的实例有关。

    所以:

  • 要么将Mother声明为interface,然后您的Embryoecluse方法就无法虚拟调用bear,因为它是静态范围内的
  • 或者,您将Mother保留为abstract class,但是需要Mother的实例(匿名或子类的实例)才能获得Embryo的实例(但除非另有说明,否则Embryo是实例范围的,并且可以虚拟地调用bear )

  • 自包含示例
    package test;
    
    public class Main {
    
        public interface MotherI {
            // this is static!
            public class Embryo {
                public void ecluse() {
                    // NOPE, static context, can't access instance context
                    // bear(this);
                }
            }
            // implicitly public abstract
            void bear(Embryo e);
        }
    
        public abstract class MotherA {
            public class Embryo {
                public void ecluse() {
                    // ok, within instance context
                    bear(this);
                }
            }
    
            public abstract void bear(Embryo e);
        }
    
        // instance initializer of Main
        {
            // Idiom for initializing static nested class
            MotherI.Embryo e = new MotherI.Embryo();
            /*
             *  Idiom for initializing instance nested class
             *  Note I also need a new instance of `Main` here,
             *  since I'm in a static context.
             *  Also note anonymous Mother here.
             */
            MotherA.Embryo ee = new MotherA() {public void bear(Embryo e) {/*TODO*/}}
               .new Embryo();
        }
    
        public static void main(String[] args) throws Exception {
            // nothing to do here
        }
    }
    

    10-07 19:11