【问题标题】:How to implement nested non-static classes in interfaces?如何在接口中实现嵌套的非静态类?
【发布时间】:2016-05-06 00:55:02
【问题描述】:

有这门课

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

只有当我有一个母亲实例时,我才能创建一个胚胎实例:

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

问题:

  • 如何将Mother定义为接口?

【问题讨论】:

标签: java interface


【解决方案1】:

嵌套类 Embryo 隐含在 interface 中的 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 的类,abstract classinterface 都不能被实例化,无论如何你需要另一个类!那么它为什么在乎呢? Embryo 的实例只能通过外部类Mother 的实例获得,如果它是接口或抽象类,
  • 不完全是最后一部分。让我举个例子。
  • 我完全理解第一句话。为什么会这样?
  • 我不需要代码示例,我已经明白你的意思了,但为什么会这样?
  • @PeterRader 我认为这只是 Java 语言规范的一部分,但我很难找到明确的参考。 interfaces 的所有成员都隐含地是 static public final。然而,interfaces 的嵌套 classes 只有 public static 而不是 final,因为它们可以扩展。
猜你喜欢
  • 2016-01-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-15
  • 1970-01-01
  • 2012-12-31
  • 1970-01-01
相关资源
最近更新 更多