简体   繁体   中英

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

ii)class B is getting loaded , so the second static block gets called , and it prints B

iii)default constructor of A (because new B is requested) so it prints a

iv) and finally default constructor of B as it was requested with new B() so it prints b , the output is ABab

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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