Java中的静态/实例初始化程序块以什么顺序运行? [英] In what order do static/instance initializer blocks in Java run?
问题描述
假设一个项目包含几个类,每个类都有一个静态初始化块。这些块以什么顺序运行?我知道在类中,这些块按照它们在代码中出现的顺序运行。我已经读过它在各个类中都是一样的,但我写的一些示例代码不同意这一点。我使用了这段代码:
Say a project contains several classes, each of which has a static initializer block. In what order do those blocks run? I know that within a class, such blocks are run in the order they appear in the code. I've read that it's the same across classes, but some sample code I wrote disagrees with that. I used this code:
package pkg;
public class LoadTest {
public static void main(String[] args) {
System.out.println("START");
new Child();
System.out.println("END");
}
}
class Parent extends Grandparent {
// Instance init block
{
System.out.println("instance - parent");
}
// Constructor
public Parent() {
System.out.println("constructor - parent");
}
// Static init block
static {
System.out.println("static - parent");
}
}
class Grandparent {
// Static init block
static {
System.out.println("static - grandparent");
}
// Instance init block
{
System.out.println("instance - grandparent");
}
// Constructor
public Grandparent() {
System.out.println("constructor - grandparent");
}
}
class Child extends Parent {
// Constructor
public Child() {
System.out.println("constructor - child");
}
// Static init block
static {
System.out.println("static - child");
}
// Instance init block
{
System.out.println("instance - child");
}
}
并获得此输出:
START
static - grandparent
static - parent
static - child
实例 - 祖父母代表
构造函数 - 祖父母代表
实例 - 父代
构造函数 - 父代
实例 - 孩子
构造函数 - 孩子
结束
START
static - grandparent
static - parent
static - child
instance - grandparent
constructor - grandparent
instance - parent
constructor - parent
instance - child
constructor - child
END
明显的答案是父母的块在之前运行他们的孩子,但这可能只是一个巧合,如果两个班级不在同一个等级中,则无济于事。
The obvious answer from that is that parents' blocks run before their children's, but that could just be a coincidence and doesn't help if two classes aren't in the same hierarchy.
编辑:
我通过将此示例代码附加到LoadTest.java来修改我的示例代码:
I modified my example code by appending this to LoadTest.java:
class IAmAClassThatIsNeverUsed {
// Constructor
public IAmAClassThatIsNeverUsed() {
System.out.println("constructor - IAACTINU");
}
// Instance init block
{
System.out.println("instance - IAACTINU");
}
// Static init block
static {
System.out.println("static - IAACTINU");
}
}
正如班级名称所暗示的那样,我从未引用过新课程。新程序产生的输出与旧程序相同。
As implied by the class name, I never referenced the new class anywhere. The new program produced the same output as the old one.
推荐答案
当类第一次运行时,类的静态初始化程序会运行访问,要么创建实例,要么访问静态方法或字段。
The static initializer for a class gets run when the class is first accessed, either to create an instance, or to access a static method or field.
因此,对于多个类,这完全取决于运行导致这些类的代码加载。
So, for multiple classes, this totally depends on the code that's run to cause those classes to get loaded.
这篇关于Java中的静态/实例初始化程序块以什么顺序运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!