如何在接口中实现嵌套非静态类?

7
拥有这个类
public abstract class Mother{
  public class Embryo{
    public void ecluse(){
      bear(this);
    }
  }
  abstract void bear(Embryo e);
}

只有在我拥有母亲的实例时,才能创建胚胎的实例。

new Mother(){...}.new Embryo().ecluse();

问题:

  • 如何将Mother定义为一个接口?

1
不完全无关,但也没有真正回答你的问题:https://dev59.com/xnE95IYBdhLWcg3wOLU1 - ctst
1
你能提供一些关于你计划如何使用这个接口/类的信息吗? - proskor
1个回答

6
嵌套类Embryointerface中隐式地被声明为static。因此,它无法访问虚拟可调用方法bear,该方法适用于您的Mother接口的实例。
因此:
  • 要么将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
    }
}

既不是抽象类也不是接口可以在没有实现Mother的类的情况下被实例化,你无论如何都需要另一个类!那么它为什么要关心呢?Embryo的实例只能通过外部类Mother的实例获得,如果它是一个接口或抽象类。 - Grim
不完全是针对最后一部分。让我给你一个例子。 - Mena
我完全理解第一句话。为什么会这样呢? - Grim
我不需要代码示例,我已经明白你的意思了,但为什么会这样呢? - Grim
1
@PeterRader 我认为这只是Java语言规范的一部分,但我在查找明确的参考时遇到了困难。所有interface成员都是隐式的static public final。但是interfaces的嵌套class仅限于public static而不是final,因为它们可以被扩展。 - Mena

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接