Search code examples
javaconstructorinitialization

Why can I call instance method in instance init block?


The instance initialisation block is invoked before constructor but this is available in it already. And so we can call any public or private methods. But why? Only the constructor guarantees the instance creation and availability of this

public class Test {

    {
        this.privatePrint();
        this.publicPrint();
    }

    public Test() {
        System.out.print(" Constructor ");
    }

    public void publicPrint() {
        System.out.print(" public ");
    }

    public void privatePrint() {
        System.out.print(" private ");
    }

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

}

The output is private public Constructor

I tested it on jdk 11 and 17

I was surprised by the behavior of the order of object initialization methods


Solution

  • The Java Language Specification (12.5 Creation of New Class Instances has the exact details.

    Basically the Java Compiler creates for your class the same bytecode as the following class (where the call to the super constructor and the instance initializers explicitly written):

    public class Test {
    
        public Test() {
            super();  // Point 3: call the super constructor
            {  // Point 4: execute instance initializers and instance variable initializers
                this.privatePrint();
                this.publicPrint();
            }
            // Point 5: Execute the rest of the body of this constructor
            System.out.print(" Constructor ");
        }
    
        public void publicPrint() {
            System.out.print(" public ");
        }
    
        public void privatePrint() {
            System.out.print(" private ");
        }
    
        public static void main(String[] args) {
            new Test();
        }
    
    }