【发布时间】: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 {}
我有以下疑问:
如果接口是隐式静态的,为什么
StaticInterfaceInsideClass的类内部允许显式static修饰符,而InterfaceOutsideClass不允许?NonStaticInterfaceInsideClass也是静态的吗?也就是说,在类内部,显式使用static或不使用它不会有任何区别,并且默认情况下接口将始终为static?为什么我们不能在非静态内部类(
InnerClassWithInterface)中有非static接口(@987654331@),但在顶级类中可以有非static(NonStaticInterfaceInsideClass)接口(ClassWithInterface)?事实上,我们甚至不能在内部类中拥有静态接口(如StaticInterfaceInsideInnerClass)。但是为什么呢?有人可以列出驱动所有这些行为的单个或最小规则吗?
【问题讨论】:
-
Member 接口是隐式静态的。不是“所有接口”。 JLS 8.5.1。在您的链接问题中查看我的评论。
-
而“非静态内部”是双重对话。根据定义,所有内部类都是非静态的。
-
1.顶级类、接口和枚举不能是静态的。语法不允许。
-
@anir 这个答案没有参考 Java 语言规范。说顶级类、接口或枚举是“静态的”完全没有意义,因为“静态”这个词在 JLS 中仅用于描述成员,不包括包成员。
-
@anir 不,我没有。
标签: java