我是Java新手,正在为OCJP考试读一本书。在本书中,非静态内部类只有在声明为static final的情况下才能具有静态成员。但是,当我尝试创建容器类的static final object
时出现编译错误。
class Logger {
private Logger() {
// private constructor for singleton
}
public class LoggerHolder { // non static inner class
public static final int x =10; // No compile here
public static final Logger logger = new Logger(); //Compile error
}
//"The field logger cannot be declared static; static fields can only be declared in static or top //level types"
public static Logger getInstance() {
return LoggerHolder.logger;
}
}
最佳答案
actual rule是静态字段必须是一个常量变量-既是final
也是原语或String
。 x
很好,因为int
是原始元素; Logger
不是。
(书中所说的只是某人的意见;对于明确的答案,您无法超越规格。)