根据this问题,我明白为什么接口(interface)是静态的。所以我尝试了以下代码:
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 {}
我有以下疑问:
如果接口(interface)是隐式静态的,为什么在
StaticInterfaceInsideClass
的类内部,允许显式static
修饰符,而对于InterfaceOutsideClass
,其不允许?NonStaticInterfaceInsideClass
也是静态的吗?也就是说,在类内部,显式使用static
或不使用它不会有任何区别,并且接口(interface)默认情况下总是static
?为什么我们不能在非静态内部类(
InnerClassWithInterface
)中拥有非静态
接口(interface)(InterfaceInsideInnerClass
),但可以拥有顶级类(ClassWithInterface
)内的非静态
(NonStaticInterfaceInsideClass
)接口(interface)?事实上,我们甚至不能在内部类中拥有静态接口(interface)(对于StaticInterfaceInsideInnerClass
)。但为什么呢?有人可以列出驱动所有这些行为的单个或最小规则吗?
最佳答案
Can someone list down single or minimal rule(s) which drive all these behaviour?
无需接口(interface)也可以观察到相同的行为;内部类(即非静态嵌套类)不能有自己的静态成员类,因此下面的代码也会给出编译错误:
class A {
// inner class
class B {
// static member class not allowed here; compilation error
static class C {}
}
}
所以“最小规则集”是:
- “如果内部类声明显式或隐式静态的成员,则会出现编译时错误,除非该成员是常量变量” ( JLS §8.1.3 )
- “成员接口(interface)是隐式静态的(第 9.1.1 节)。允许成员接口(interface)的声明冗余地指定
static
修饰符。” ( JLS §8.5.1 )里>
使用这两个规则我们可以解释一切:
-
NonStaticInterfaceInsideClass
是一个成员接口(interface),因此根据规则 2 它是隐式静态的。 -
InterfaceInsideInnerClass
是一个成员接口(interface),因此根据规则 2,它是隐式静态的。它是内部类的成员,因此根据规则 1,它是一个编译时错误。 -
StaticInterfaceInsideInnerClass
语义上与InterfaceInsideInnerClass
相同;static
根据规则 2,修饰符是多余的。 -
InterfaceInsideStaticNestedClass
是一个成员接口(interface),因此规则 2 中它是隐式静态的,但规则 1 中不禁止它,因为它是静态嵌套类的成员,而不是内部类。 -
InterfaceOutsideClass
不允许static
修饰符,因为它不是成员接口(interface),并且规则 2 只允许 member 接口(interface)具有static
修饰符。
关于java - 理解java中接口(interface)的静态性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60366253/