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

public class Test {

private static final int A;

static {

A = 5;

}

}

This way of initializing static final variable A works okay .

public class Test {

private static final int A;

static {

Test.A = 5;

}

}

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

Why?

解决方案

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, static initializer, or

static variable initializer of C.

In layman's terms:

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.

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值