内部 class 允许静态字段和非常量静态表达式 - 为什么?
Inner class allows static fields and non constant static expression - Why?
根据 JLS :
An inner class is a nested class that is not explicitly or implicitly
declared static. Inner classes may not declare static initializers
or member interfaces.
但是我下面的代码编译成功了。
class A {
interface B {
class C { // Inner class having static variables.
static int d; // Static variable
static {
}
}
}
}
谁能帮我理解这种行为
嵌套接口是隐式静态的,并且本身没有非静态上下文,这就是 C 是隐式静态的原因。
你可以在一个接口里面定义一个class。在接口内部,内部 class 隐式 public 是静态的。 ... Interfaces may contain member type declarations 接口中的成员类型声明是隐式静态的并且 public.
所以我们不能将非静态成员声明到静态块、静态方法 或 static class.
找到相同的 JLS 规范:
8.5.2 - "Member interfaces are always implicitly static"
9.5 - "Interfaces may contain member type declarations (§8.5). A member type declaration in an interface is implicitly static and
public"
这意味着上面的代码在道德上等同于(隐式修饰符以大写字母书写):
class A {
STATIC interface B {
PUBLIC STATIC class C { //It's a static class - that's why static members are legal (like a toplevel class but nested)
static int d; //Static variable
static {} //Static initializer
}
}
}
根据 JLS :
An inner class is a nested class that is not explicitly or implicitly declared static. Inner classes may not declare static initializers or member interfaces.
但是我下面的代码编译成功了。
class A {
interface B {
class C { // Inner class having static variables.
static int d; // Static variable
static {
}
}
}
}
谁能帮我理解这种行为
嵌套接口是隐式静态的,并且本身没有非静态上下文,这就是 C 是隐式静态的原因。
你可以在一个接口里面定义一个class。在接口内部,内部 class 隐式 public 是静态的。 ... Interfaces may contain member type declarations 接口中的成员类型声明是隐式静态的并且 public.
所以我们不能将非静态成员声明到静态块、静态方法 或 static class.
找到相同的 JLS 规范:
8.5.2 - "Member interfaces are always implicitly static"
9.5 - "Interfaces may contain member type declarations (§8.5). A member type declaration in an interface is implicitly static and public"
这意味着上面的代码在道德上等同于(隐式修饰符以大写字母书写):
class A {
STATIC interface B {
PUBLIC STATIC class C { //It's a static class - that's why static members are legal (like a toplevel class but nested)
static int d; //Static variable
static {} //Static initializer
}
}
}