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

前端之家收集整理的这篇文章主要介绍了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
     }
  }
}

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

猜你在找的Java相关文章