public class Test { private static final int A; static { A = 5; } }
这种初始化静态最终变量A的方法没问题.
public class Test { private static final int A; static { Test.A = 5; } }
这种方式会产生编译错误“无法为最终变量’A’赋值.
为什么?
解决方法
Let C be a class,and let V be a blank
static final
member field of C,
declared in C. Then:
V is definitely unassigned (and moreover is not definitely assigned) before the leftmost enum constant,static initializer
(§8.7),or static variable initializer of C.V is [un]assigned before an enum constant,static initializer,or static variable initializer of C other than the leftmost iff V is
[un]assigned after the preceding enum constant,or
static variable initializer of C.
通俗地说:
>使用静态初始化程序通过引用其简单名称初始化静态最终字段是正常的,因为该字段在初始化程序之后是明确赋值的.实际上,在声明静态初始化程序的类中有上下文,并且您没有通过简单名称引用该字段来执行任何非法赋值;相反,您正在满足必须明确分配字段的要求.>使用静态初始化程序通过引用其限定名称来初始化静态final字段是非法的,因为在引用它的静态属性时必须初始化该类(在您的情况下,必须在之前初始化Test.A,并指定A完成初始化后的默认值为null).
原文地址:https://www.jb51.cc/java/239985.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。