【发布时间】:2013-06-19 16:35:01
【问题描述】:
在方法内部声明局部内部类时,为什么包含 final static Strings 或 int 是合法的,但包含其他对象是不合法的?
例如:
class Outer {
void aMethod() {
class Inner {
final static String name = "compiles";
final static int ctr = 10; // compiles
final static Integer intThree = Integer.valueOf(3); // does not compile!
final static obj objConst = new Object(); // does not compile!
}
Inner inner = new Inner();
}
}
当我编译这个时,我得到以下信息:
InnerExample.java:6: inner classes cannot have static declarations
final static Integer outer = Integer.valueOf(3);
^
InnerExample.java:7: inner classes cannot have static declarations
final static Object objConst = new Object();
^
为什么要区分?是因为 String 是不可变的吗?如果是这样,Integer.valueOf() 不是也有效吗?
【问题讨论】:
-
我很确定这是因为“compiles”和 10 是编译时常量表达式,但我还没有找到 JLS 规则。
标签: java inner-classes final static-members