在java中初始化静态最终变量

参见英文答案 > Why isn’t a qualified static final variable allowed in a static initialization block?2个
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’赋值.

为什么?

解决方法

rules for Definite Assignment指定:

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).

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...