Why are instance initialization blocks executed before constructors

人走茶凉 提交于 2019-12-19 03:36:45

问题


I know that static blocks are initialized at the time the class is loaded and since the class is loaded only once in a program,they are initialized only once.

IIB (Instance initialization blocks) are initialized every time an instance of the class is made, and the same for constructors: they are executed during object creation.

I don't understand why in the below program IIB is executed in prior to Constructors. Code-

public class Hello {

    public static void main(String args[]) {
        C obj = new C();
    }
}

class A {

    static {
        System.out.println("Inside static block of A");
    }

    {
        System.out.println("Inside IIB of A");
    }

    A() {
        System.out.println("Inside NO-ARGS constructor of A");
    }
}

class B extends A {

    static {
        System.out.println("Inside static block of B");
    }

    {
        System.out.println("Inside IIB of B");
    }

    B() {
        System.out.println("Inside NO-ARGS constructor of B");
    }
}
class C extends B {

    static {
        System.out.println("Inside static block of C");
    }

    {
        System.out.println("Inside IIB of C");
    }

    C() {
        System.out.println("Inside NO-ARGS constructor of C");
    }
}

Why IIB is executed first compared to constructors?


回答1:


Java compiler injects initializer blocks at the beginning of your constructors (after calling a superconstructor). To give you a better understanding I've compiled the following class

public class Foo extends SuperFoo {
    private String foo1 = "hello";
    private String foo2;
    private String foo3;
    {
        foo2 = "world";
    }
    public Foo() {
        foo3 = "!!!";
    }
}

and run it through a javap decompiler:

Compiled from "Foo.java"
public class Foo extends SuperFoo {
  private java.lang.String foo1;
  private java.lang.String foo2;
  private java.lang.String foo3;
  public Foo();
    Code:
       0: aload_0
       1: invokespecial #12                 // Method SuperFoo."<init>":()V
       4: aload_0
       5: ldc           #14                 // String hello
       7: putfield      #16                 // Field foo1:Ljava/lang/String;
      10: aload_0
      11: ldc           #18                 // String world
      13: putfield      #20                 // Field foo2:Ljava/lang/String;
      16: aload_0
      17: ldc           #22                 // String !!!
      19: putfield      #24                 // Field foo3:Ljava/lang/String;
      22: return
}


来源:https://stackoverflow.com/questions/31101110/why-are-instance-initialization-blocks-executed-before-constructors

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!