According to this question, I understand that why interfaces are static. So I tried out following code:
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 {}
I have following doubts:
If interfaces are implicitly static, why inside class for
StaticInterfaceInsideClass, explicitstaticmodifier is allowed, whereas forInterfaceOutsideClass, its not allowed?Is
NonStaticInterfaceInsideClassis also static? That is, inside class, explicitly usingstaticor not using it will not have any difference and interface will always bestaticby default?Why we cant have non-
staticinterface (InterfaceInsideInnerClass) inside non static inner class (InnerClassWithInterface), but can have non-static(NonStaticInterfaceInsideClass) interface inside top level class (ClassWithInterface)? In fact, we cant even have static interface inside inner class (as forStaticInterfaceInsideInnerClass). But why?Can someone list down single or minimal rule(s) which drive all these behavior?