简体   繁体   English

JAVA中涉及静态初始化程序和继承时,执行的顺序是什么?

[英]What is the order of execution when static initializer and inheritance is involved in JAVA?

I ran across this code: 我遇到了以下代码:

public class A {
    static{
        System.out.print("A");
    }

    A(){
        System.out.print("a");
    }
}

public class B extends A {
    static{
        System.out.print("B");
    }

    B(){
        System.out.print("b");
    }
}

public class Test {
    public static void main(String[] args) {
        new B();
    }
}

My understanding of order of object construction is: 我对对象构造顺序的理解是:

  1. Initialize member fields of the base class(es) 初始化基类的成员字段
  2. Run the base class(es) constructor(s) 运行基类的构造函数
  3. Initialize member fields of sub class 初始化子类的成员字段
  4. Run the constructor of sub class 运行子类的构造函数

And my understanding of execution of static initializer is 我对静态初始化程序的执行的理解是

  • 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. 首次访问该类时,该类的静态初始化程序将运行,以创建实例或访问静态方法或字段。

But I can not come up with the correct printing, i got: 但是我无法提出正确的打印,我得到了:

A(base initialzer)
a(base constructor)
B(subclass initialize)
b(subclass constructor)

Could someone explain what is the correct order and why? 有人可以解释正确的顺序是什么,为什么?

Update 更新资料

static blocks will called whenever the class is loaded by the classloader , thus the correct order is : 当类加载器加载类时,将调用静态块,因此正确的顺序是:

i) class A is loaded (because B extends A is requested) so the first static block is called , and it prints A i)加载了类A(因为请求了B extends A ),所以第一个静态块被调用,并输出A

ii)class B is getting loaded , so the second static block gets called , and it prints B ii)正在加载类B,因此调用了第二个静态块,并输出B

iii)default constructor of A (because new B is requested) so it prints a iii)A的默认构造函数(因为需要新的B),因此它会打印a

iv) and finally default constructor of B as it was requested with new B() so it prints b , the output is ABab iv)最后是new B()请求的B的默认构造函数,因此它输出b,输出为ABab

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

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