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

前端之家收集整理的这篇文章主要介绍了在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).

原文链接:https://www.f2er.com/java/239985.html

猜你在找的Java相关文章