嵌套在接口中的类

时间:2013-10-17 16:52:05

标签: java interface static nested-class jls

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

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

以下编译:

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的嵌套类是否也隐式静态?

再一次,StaticNestedClassInnerClass是一样的吗?

1 个答案:

答案 0 :(得分:3)

class InnerClass 

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

  

接口中的成员类型声明是隐式静态的   上市。允许冗余地指定其中一个或两个   改性剂。

static class InnerClass

因为它在界面中。

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

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

是的,StaticNestedClassInnerClass是相同的

相关问题