Java 静态代码块、代码块、构造方法和多态继承的代码执行顺序

  • 测试代码
import lombok.Getter;

public class ExecutionOrder {
    {
        System.out.println("ExecutionOrder code 0");
    }
    static {
        System.out.println("ExecutionOrder static code");
    }
    {
        System.out.println("ExecutionOrder code 2");
    }
    public ExecutionOrder() {
        System.out.println("ExecutionOrder construction");
    }
    public static void main(String[] args) {
        AbsBase child = new Child();
        child.func();
        System.out.println("result: k = " + child.getK());
        System.out.println("result: i, j, k = " + child.i + " - " + child.j + " - " + child.k);
    }

}

abstract class AbsBase {
    int i = 1;
    int j = 2;
    @Getter
    int k;
    {
        System.out.println("AbsBase code 0");
    }
    static {
        System.out.println("AbsBase static code");
    }
    {
        System.out.println("AbsBase code 2");
    }
    public AbsBase() {
        System.out.println("AbsBase construction");
    }
    abstract void func();
}

class Parent extends AbsBase {
    int i = 3;
    int j = 4;
    @Getter
    int k = -1;
    {
        System.out.println("Parent code 0");
    }
    static {
        System.out.println("Parent static code");
    }
    {
        System.out.println("Parent code 1");
    }
    Parent() {
        System.out.println("Parent construction");
    }
    @Override
    public void func() {
        System.out.println("Parent this.getK(): " + this.getK());
        System.out.println("Parent super.getK(): " + super.getK());
        System.out.println("Parent.func(): " + i + " - " + j + " - " + k);
    }
}

class Child extends Parent {
    int i = 5;
    int j = 6;
    @Getter
    int k = -2;
    {
        System.out.println("Child code 0");
    }
    static {
        System.out.println("Child static code");
    }
    {
        System.out.println("Child code 1");
    }
    Child() {
        System.out.println("Child construction");
    }
    @Override
    public void func() {
        System.out.println("Child this.getK(): " + this.getK());
        System.out.println("Child super.getK(): " + super.getK());
        System.out.println("Child.func(): " + i + " - " + j + " - " + k);
    }
}
  • 执行结果
ExecutionOrder static code
AbsBase static code
Parent static code
Child static code
AbsBase code 0
AbsBase code 2
AbsBase construction
Parent code 0
Parent code 1
Parent construction
Child code 0
Child code 1
Child construction
Child this.getK(): -2
Child super.getK(): -1
Child.func(): 5 - 6 - -2
result: k = -2
result: i, j, k = 1 - 2 - 0

Process finished with exit code 0

posted @ 2023-10-29 12:41  MoonTwilight  阅读(6)  评论(0编辑  收藏  举报