在非静态内部类中的静态最终对象编译错误
问题描述:
我是Java新手,为我的OCJP考试阅读一本书。在本书中,它声明的非静态内部类只有声明为静态最终时才可以有静态成员。但是当我尝试创建容器类的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
不是。
(什么是书上说的只是有人的意见;对于确定的答案,你不能击败规范)
+0
伟大的答案和感谢您的链接。它现在有道理... – 2014-12-27 20:55:40
的'logger'在编译时间,这就是为什么它是不允许知道。 – 2014-12-27 15:04:49
Mhh,'Logger'和'Logger4' ...哪里可能出现问题? – Tom 2014-12-27 15:20:27
@汤姆哦...对不起,我的坏....那是复制粘贴错误。我现在编辑它... – 2014-12-27 20:49:34