本文介绍了使用继承时,静态块和初始化块以什么顺序执行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个班级 Parent 和 Child

I have two classes Parent and 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 会按照这个顺序执行代码?决定执行顺序的规则是什么?

Why does Java execute the code in that order? What are the rules that determine the execution order?

推荐答案

我通过视觉学习,所以这里有一个秩序的视觉表示,作为 SSCCE:

I learn visually, so here's a visual representation of order, as a 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的顺序的区别.

Keep in mind that the order of the static parts matters; look back at the difference between the order of Example's static stuff and ExampleSubclass's.

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

Also note that the instance initialization block is always executed immediately after the super() call in the constructor (even if that call is implied/omitted), no matter the order. However, order does matter between an initialization block and a field initializer.

这篇关于使用继承时,静态块和初始化块以什么顺序执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 02:43