在方法中声明本地内部类时,为什么包含 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() 不是也有效吗?