gpt4 book ai didi

java - 使用继承时,静态 block 和初始化 block 按什么顺序执行?

转载 作者:IT老高 更新时间:2023-10-28 11:45:53 24 4
gpt4 key购买 nike

我有两个类 Parent 和 Child

public class Parent {    
public Parent() {
System.out.println("Parent Constructor");
}
static {
System.out.println("Parent static block");
}
{
System.out.println("Parent initialisation block");
}
}

public class Child extends Parent {
{
System.out.println("Child initialisation block");
}
static {
System.out.println("Child static block");
}

public Child() {
System.out.println("Child Constructor");
}
public static void main(String[] args) {
new Child();
}
}

上述代码的输出将是

Parent static block
Child static block
Parent initialization block
Parent Constructor
Child initialization block
Child Constructor

为什么 Java 会按此顺序执行代码?决定执行顺序的规则是什么?

最佳答案

我在视觉上学习,所以这里是顺序的视觉表示,作为 SSCCE :

public class Example {

static {
step(1);
}

public static int step_2 = step(2);
public int step_8 = step(8);

public Example(int unused) {
super();
step(10);
}

{
step(9);
}

// Just for demonstration purposes:
public static int step(int step) {
System.out.println("Step " + step);
return step;
}
}
public class ExampleSubclass extends Example {

{
step(11);
}

public static int step_3 = step(3);
public int step_12 = step(12);

static {
step(4);
}

public ExampleSubclass(int unused) {
super(step(7));
step(13);
}

public static void main(String[] args) {
step(5);
new ExampleSubclass(step(6));
step(14);
}
}

打印出来:

Step 1
Step 2
Step 3
Step 4
Step 5
Step 6
Step 7
Step 8
Step 9
Step 10
Step 11
Step 12
Step 13
Step 14

请记住,static 部分的顺序很重要;回头看看Examplestatic东西和ExampleSubclass的顺序的区别。

还要注意,无论顺序如何,实例初始化 block 总是在构造函数中的 super() 调用之后立即执行(即使该调用是隐含/省略的)。但是,初始化 block 和字段初始化器之间的顺序确实很重要。

关于java - 使用继承时,静态 block 和初始化 block 按什么顺序执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19561332/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com