【问题标题】:Classes nested into an interface嵌套在接口中的类
【发布时间】:2013-10-26 07:08:00
【问题描述】:

为什么可以在接口中定义内部(又名非静态嵌套)类?

这有意义吗?它们不能存在于包含接口的实例中,因为接口不能被实例化,所以...

以下编译:

interface MyInterface
{
    static class StaticNestedClass
    {
        static int a()
        {
            return 0;
        }
        int b()
        {
            return 1;
        }
    }
    class InnerClass
    {
        static int a()
        {
            return 0;
        }
        int b()
        {
            return 1;
        }
    }
}

以上两个类有什么区别吗? static 是否真的考虑在内? 请注意,如果您将interface 更改为class,您显然会在InnerClass'static int a() 上遇到编译错误。

此外,请看以下内容:

interface MyInterface
{
    int c=0;
    static class StaticNestedClass
    {
        static int a()
        {
            return c;
        }
        int b()
        {
            return c+1;
        }
    }
    class InnerClass
    {
        static int a()
        {
            return c;
        }
        int b()
        {
            return c+1;
        }
    }
}

与外部包含实体是一个类不同,这里当然没有“内部(非静态嵌套)类可以访问外部的字段而静态嵌套类可以” t",因为鉴于我们的外部事物是一个接口,我们的 c 整数是隐式静态的...interface 的嵌套类也是隐式静态的吗?

再说一遍,StaticNestedClass 和 InnerClass 是一样的吗?

【问题讨论】:

  • 我认为 class InnerClass 是隐式静态的,类似于c
  • @Cruncher 实际上,接口中的任何非方法都会被编译器自动标记为static。

标签: java interface static nested-class jls


【解决方案1】:
class InnerClass 

是隐式的(由编译器根据JLS, Section 9.5转换为)

接口中的成员类型声明是隐式静态的,并且 民众。允许冗余指定其中一个或两个 修饰符。

static class InnerClass

因为它在一个界面中。

将接口更改为类时会出现错误,因为不允许使用非静态内部类,并且在类的情况下不会隐式转换为静态。

直接回答你的最后一个问题,

是的,StaticNestedClass 和 InnerClass 是一样的

【讨论】:

  • The JLS, Section 9.5 谈到接口成员隐式为static,其中包括成员类。
  • @rgettman 我正在寻找特定的 JLS 部分。我遇到了那个,并且不确定那部分是否涵盖内部类。谢谢,将添加到帖子中。编辑:没关系,我在 9.3,9.5 对此相当明确
  • 谢谢 Cruncher 和 rgettman,JLS 9.5 部分正是我想要的。
猜你喜欢
  • 1970-01-01
  • 2012-02-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-01
相关资源
最近更新 更多