在java中初始化静态最终变量 [英] Initializing static final variables in java

查看:220
本文介绍了在java中初始化静态最终变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public class Test {

    private static final int A;

    static {
        A = 5;
    }
}

这种初始化静态最终变量A的方法没问题。

This way of initializing static final variable A works okay .

public class Test {
    private static final int A;

    static {
        Test.A = 5;
    }   
}

这种方式会产生编译错误无法为最终变量'A'。

This way gives compile error "Cannot assign a value to final variable 'A'.

为什么?

推荐答案

指定者定义分配规则


设C为一个类,让V为空静态最终成员字段C,
在C中声明。然后:

Let C be a class, and let V be a blank static final member field of C, declared in C. Then:


  • V绝对是未分配的(而且不是绝对的在最左边的枚举常量,静态初始值设定项
    (第8.7节)或C的静态变量初始值设定项之前。

  • 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是[un]赋值除了最左边的iff V之外的枚举常量,静态初始化器或C的静态变量初始化器之前,在前面的枚举常量,静态初始化器或
静态变量初始化器之后分配
[un]。 / p>

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, static initializer, or static variable initializer of C.

在外行人的条款中:


  • 使用静态初始化程序通过引用其简单名称来初始化 static final 字段是正常的,因为该字段在初始化程序之后是明确赋值的。实际上,在声明静态初始化程序的类中有上下文,并且您没有通过简单名称引用该字段来执行任何非法赋值;相反,您正在满足必须明确分配字段的要求。

  • Using a static initializer to initialize a static final field by referencing its simple name is OK since that field is definitely assigned after the initializer. Effectively, there's context into the class in which the static initializer is declared in, and you are not performing any illegal assignment by referring to the field by its simple name; instead, you're fulfilling the requirement that the field must be definitely assigned.

使用静态初始化程序初始化静态最终字段通过引用其限定名称是非法的,因为类必须在引用它的静态属性时进行初始化(在您的情况下, Test.A 必须之前进行初始化,并且 A 被分配默认值 null 完成初始化后。)

Using a static initializer to initialize a static final field by referencing its qualified name is illegal, since the class must be initialized when referring to a static property of it (in your case, Test.A must be initialized prior, and A is assigned the default value of null upon completion of initialization).

这篇关于在java中初始化静态最终变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆