加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-14 17:41:32 所属栏目: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
好的,我知道这是规则:

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
     }
  }
}

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读