【问题标题】:Understanding static-ness of interfaces in java了解java中接口的静态性
【发布时间】:2020-02-23 19:57:00
【问题描述】:

根据this 的问题,我明白为什么接口是静态的。所以我尝试了以下代码:

public class ClassWithInterface {
    static interface StaticInterfaceInsideClass {   }

    interface NonStaticInterfaceInsideClass {   }

    //interface is not allowed inside non static inner classes
    //Error: The member interface InterfaceInsideInnerClass can 
    //only be defined inside a top-level class or interface or 
    //in a static context
    class InnerClassWithInterface {
        interface InterfaceInsideInnerClass {}
    }

    //Error: The member interface StaticInterfaceInsideInnerClass 
    //can only be defined inside a top-level class or interface or 
    //in a static context
    class InnerClassWithStaticInterface {
        static interface StaticInterfaceInsideInnerClass {}
    }

    static class StaticNestedClassWithInterface {
        interface InterfaceInsideStaticNestedClass {}
    }
}

//Static is not allowed for interface outside class
//Error: Illegal modifier for the interface 
//InterfaceOutsideClass; only public & abstract are permitted
static interface InterfaceOutsideClass {}

我有以下疑问:

  1. 如果接口是隐式静态的,为什么StaticInterfaceInsideClass的类内部允许显式static修饰符,而InterfaceOutsideClass不允许?

  2. NonStaticInterfaceInsideClass 也是静态的吗?也就是说,在类内部,显式使用static 或不使用它不会有任何区别,并且默认情况下接口将始终为static

  3. 为什么我们不能在非静态内部类(InnerClassWithInterface)中有非static接口(@98​​7654331@),但在顶级类中可以有非staticNonStaticInterfaceInsideClass)接口(ClassWithInterface)?事实上,我们甚至不能在内部类中拥有静态接口(如StaticInterfaceInsideInnerClass)。但是为什么呢?

  4. 有人可以列出驱动所有这些行为的单个或最小规则吗?

【问题讨论】:

  • Member 接口是隐式静态的。不是“所有接口”。 JLS 8.5.1。在您的链接问题中查看我的评论。
  • 而“非静态内部”是双重对话。根据定义,所有内部类都是非静态的。
  • 1.顶级类、接口和枚举不能是静态的。语法不允许。
  • @anir 这个答案没有参考 Java 语言规范。说顶级类、接口或枚举是“静态的”完全没有意义,因为“静态”这个词在 JLS 中仅用于描述成员,不包括包成员。
  • @anir 不,我没有。

标签: java


【解决方案1】:

有人可以列出驱动所有这些行为的单一或最小规则吗?

没有接口也可以观察到相同的行为;内部类(即非静态嵌套类)不能有自己的静态成员类,所以下面的代码也会出现编译错误:

class A {
    // inner class
    class B {
        // static member class not allowed here; compilation error
        static class C {}
    }
}

所以“最小规则集”是:

  1. “如果内部类声明一个显式或隐式静态成员,则这是编译时错误,除非该成员是常量变量” (JLS §8.1.3)
  2. “成员接口是隐式静态的(第 9.1.1 节)。允许成员接口的声明冗余地指定 static 修饰符。” (JLS §8.5.1)

使用这两条规则我们可以解释一切:

  • NonStaticInterfaceInsideClass 是一个成员接口,因此根据规则 2 它是隐式静态的。
  • InterfaceInsideInnerClass 是成员接口,因此根据规则 2 它是隐式静态的。它是内部类的成员,因此根据规则 1 是编译时错误。
  • StaticInterfaceInsideInnerClass 在语义上与InterfaceInsideInnerClass 相同;根据规则 2,static 修饰符是多余的。
  • InterfaceInsideStaticNestedClass 是一个成员接口,所以它在规则 2 中是隐式静态的,但它不受规则 1 的禁止,因为它是静态嵌套类的成员,而不是内部类。
  • InterfaceOutsideClass 不允许使用 static 修饰符,因为它不是成员接口,并且规则 2 只允许 member 接口具有 static 修饰符。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-12-16
    • 2014-06-02
    • 1970-01-01
    • 2012-01-12
    • 2013-08-16
    • 2014-11-21
    • 1970-01-01
    相关资源
    最近更新 更多