微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

原文地址:https://www.jb51.cc/java/124207.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐