简体   繁体   English

带有静态成员的java初始化顺序

[英]java initialization order with static members

I am not sure whether I have a correct model of Java initialization mechanism in my head. 我不确定我的脑中是否有正确的Java初始化机制模型。 Each class follows the following: 每个类都遵循以下内容:

  1. Initialize superclass, if there exists one 如果存在超类,则初始化超类
  2. Initialize yourself 初始化自己

Initialize follows the following: Initialize遵循以下内容:

  1. Initialize static and instance variables which have their values set outside of initializer. 初始化静态和实例变量,其值设置在初始化程序之外。
  2. Run static initialization block 运行静态初始化块
  3. Run constructor block 运行构造函数块

Is that precise/correct? 这是准确/正确的吗?

According to the Java language specification , your assumptions are more or less correct. 根据Java语言规范 ,您的假设或多或少是正确的。 The exceptions are that: 例外是:

  1. instance variables are run when the class is constructed (together with the constructor) after the class is initialized, 在初始化类之后构造类(与构造函数一起)时运行实例变量,
  2. final static variables with compile-time constant expressions are loaded before even attempting to load the superclass, and 带有编译时常量表达式的最终静态变量在尝试加载超类之前加载,并且
  3. the static initialization block is run together with the static variables as one block, in the order they appear in the code. 静态初始化块与静态变量一起作为一个块运行,按它们在代码中出现的顺序。

Code execute as below - 代码执行如下 -

Static init blocks run once, when the class is first loaded. 首次加载类时,静态初始化块运行一次。

Static Variable 静态变量

All Super Constructor. 所有超级构造者。

Instance init blocks run after the constructor's call to super(). 实例初始化块在构造函数调用super()之后运行。

instance variable. 实例变量。

(Init blocks execute in the order they appear.) (Init块按它们出现的顺序执行。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM