7

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

1 Answer 1

10

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
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.