JAVA initialization blocks

后端 未结 6 1786
谎友^
谎友^ 2021-01-21 18:03

As some sources say, the Java instance initialization blocks are executed whenever instance is created or right before constructor. But imagine this case:

public         


        
6条回答
  •  星月不相逢
    2021-01-21 18:38

    See how this code works internally :

    class Foo {
    
        {System.out.println("Foo init");}
    
        public Foo()
        {
    
            {System.out.println("Foo constr");}
        }
    }
    
    
    
    class Main extends Foo {
    
        {System.out.println("Main init");}
    
        public Main()
        {
    
            {System.out.println("Main constr");}
        }
        public static void main(String[] args) {
    
            new Main();
        }
    }
    

    Step 1 : The JVM calls the main() method of Main class

    Step 2 : Constructor Main() have internally super() which is given by JVM if you are not using this(), hence super will call super class constructor i.e Foo() of super class.

    Step 3 : Now before calling the Foo of super class, the JVM will check is there any IIB i.e instance initialization Block, hence, "Foo init" will be printed before printing the "Foo constr"

    Now output till now is :

    Foo init 
    Foo constr
    

    Step 4: Our control come back to the current constructor and again before execution the current construstor JVM will call IIB i.e instance initialization Block and "Main init" will be printed. Then finally "Main constr"

    So Finally out is :

    Foo init
    Foo constr
    Main init
    Main constr
    

    Actually the first call of any Constructor is always Super() or this(). you are creating new object using new Main(); and of course this will give call to constructor, Constructor is always called to initialize the object.

提交回复
热议问题