在方法内部声明局部内部类时,为什么包含最终的静态String或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()也无效吗?