JAVA initialization blocks

后端 未结 6 1744
谎友^
谎友^ 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:35

    No. The initialization blocks are copied directly into the constructor(s). Obviously there is an implicit super in there as well. So your example becomes

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

    Which explains your observed behavior of

    Foo init
    Foo constr
    Main init
    Main constr
    

提交回复
热议问题