java – 为什么界面只能在顶级类中声明?

好的,我知道这是规则:

According to JLS: 8.1.3 Inner Classes and Enclosing Instances,inner
classes may not declare static initializers or member interfaces.
Inner classes may not declare static members,unless they are
compile-time constant fields.

According to 8.5.2 Static Member Type Declarations,“Member interfaces
are always implicitly static. It is permitted but not required for the
declaration of a member interface to explicitly list the static
modifier”. They are always top-level,not inner.

我只是想知道为什么如果允许在内部类中声明接口,可能会发生什么?如果我把它放到另一个Class文件中,内部类不会成为顶级类吗?

解决方法

Won’t inner class become top-level class if I put it into another Class file?

不,它仍然是一个内部类,文件名指示(IIRC它是OuterClass $InnerClass.class).

内部类可以访问外部类的属性,即它们依赖于它们的外部类’实例.使用界面,您无法做到这一点.想到一个完全不相关的类,必须由相应的外部类’实例创建.如果外部类不知道谁实现了该接口,那该怎么做?

您可以做的是在外部类中声明静态接口,因此仅将外部用作命名空间:

public class OuterClass {
  public static interface InnerInterface { //protected and private would be fine too,depending on what makes sense
  }
}

编辑:实际上,我误解了问题,因为界面是静态的,这里是一个更新的代码片段:

public class OuterClass {
  public static InnerClass { //static inner class making OuterClass just be a namespace
     public interface InnerInnerInterface { //protected and private would be fine too,depending on what makes sense
     }
  }
}

作为一种解决方法,您可以定义一个抽象内部内部类,其缺点是您必须坚持单个继承约束.

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...