java字段顺序,java – 最终字段初始化顺序

App.main()中的A.f()触发类A的初始化。

所有常量变量都被初始化。唯一的常数变量是S1,现在是1。

然后,其他静态字段按文本顺序初始化。 b是第一个字段,触发B类的初始化,依次调用A.f()。 S2只是null,因为它还没有初始化。 b的初始化现在完成。最后但并非最不重要的是,S2被初始化为整数对象2。

S2不是常量变量,因为它不是原始类型int,而是参考类型Integer。 S2 = 2;是S2 = Integer.valueOf(2);的自动装箱简写。

If a declarator in a field declaration has a variable initializer, then the declarator has the semantics of an assignment (§15.26) to the declared variable.

[…]

Note that static fields that are constant variables (§4.12.4) are initialized before other static fields (§12.4.2). This also applies in interfaces (§9.3.1). Such fields will never be observed to have their default initial values (§4.12.5), even by devious programs.

A constant variable is a final variable of primitive type or type String that is initialized with a constant expression (§15.28). Whether a variable is a constant variable or not may have implications with respect to class initialization (§12.4.1), binary compatibility (§13.1, §13.4.9), and definite assignment (§16 (Definite Assignment)).

A constant expression is an expression denoting a value of primitive type or a String that does not complete abruptly and is composed using only the following:

Literals of primitive type and literals of type String

[…]

For each class or interface C, there is a unique initialization lock LC. The mapping from C to LC is left to the discretion of the Java Virtual Machine implementation. The procedure for initializing C is then as follows:

[…]

Otherwise, record the fact that initialization of the Class object for C is in progress by the current thread, and release LC.

Then, initialize the static fields of C which are constant variables (§4.12.4, §8.3.2, §9.3.1).

[…]

Next, execute either the class variable initializers and static initializers of the class, or the field initializers of the interface, in textual order, as though they were a single block.

Every variable in a program must have a value before its value is used:

Each class variable, instance variable, or array component is initialized with a default value when it is created (§15.9, §15.10.2):

[…]

For all reference types (§4.3), the default value is null.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值