javaconstructorstatic-block

Java - Why the instance block is called after the constructor or order wise in the constructor?


As we know that the instance block is called before the constructor. Specifications, Stack Overflow Answer etc.

So, the output that we expect from the code below:

class Test{
    static { System.out.println("Static Block"); }
    { System.out.println("Instance Block"); }
    Test(){
        System.out.println("Constructor Body");
        { System.out.println("Constructor Instance Block"); }
    }
}
class TestApp{
    public static void main(String[] args){
        new Test();
    }
} 

Should Be:

Static Block
Instance Block

Constructor Instance Block
Constructor Body

Then why i am getting the following output:

Static Block
Instance Block

Constructor Body
Constructor Instance Block

But if i change the order of the statements in constructor like:

class Test{
    static { System.out.println("Static Block"); }
    { System.out.println("Instance Block"); }
    Test(){
        { System.out.println("Constructor Instance Block"); }
        System.out.println("Constructor Body");
    }
}

Then it outputs the expected result but this should not be the way because the docs says that instance block is called before the constructor.

Why the instance block is called after the constructor body or we can say why it is called in order wise ?


Solution

  • { System.out.println("Constructor Instance Block"); } is not an instance block, but yet another common line of code in a method(in your case, the constructor). So it excute AFTER the System.out.println("Constructor Body"); , which is natural.