[英]Java Compiler error puzzler: “inner classes cannot have static declarations” - except for simple types
While coding, I have encountered a strange Java Compiler behaviour. 编码时,我遇到了一个奇怪的Java编译器行为。
When compiling the class (source below), the compiler emits an error (" inner classes cannot have static declarations
") on the NULL class variable. 在编译类(下面的源代码)时,编译器会在NULL类变量上发出错误(“
inner classes cannot have static declarations
”)。 This is as expected! 这是预期的!
However, no error is generated on the ZERO class variable. 但是,ZERO类变量不会生成错误。 This I don't understand!
这个我不明白!
Why this difference, which seems to allow static declarations of simple types, but not Objects, in inner classes. 为什么这种差异似乎允许内部类中的简单类型而不是对象的静态声明。
(javac -version: 1.6.0_24)
(javac -version:1.6.0_24)
public class Outer {
public static final Runnable HELLO = new Runnable() {
// No compiler error
public static final int ZERO = 0;
// Causes compiler error: "inner classes cannot have static declarations"
public static final Object NULL = null;
@Override
public void run() {
System.out.println("Hello " + ZERO + NULL);
}
};
}
问题是内部类不能有一个静态初始化块,这是初始化非平凡常量和非常量所必需的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.