The order of execution of the block of code in the class

First, what is the code block

  In Java, using {} enclosed code is called a code block. Depending on the location, divided into local code block, code block, and a static configuration code blocks

    • Partial block: appears in the process; life cycle defined variables, early release, improve memory utilization
    • Configuration code block (initialization block): outside of class methods; a plurality of methods in the same configuration codes stored together, are configured to perform each call, and before performing the constructor
    • Static block of code: class methods appear outside, and add static modification; for a class is initialized, is executed when loaded and executed only once.
    • Generally used for loading drivers
. 1  Package Day01;
 2  
. 3  public  class Test1 {
 . 4  
. 5      public  static  void main (String [] args) {
 . 6          Zi = zi and new new Zi ();
 . 7      }
 . 8  }
 . 9  
10  class Fu {
 . 11      static {
 12 is          System.out.println ( "parent static block of code" );
 13 is      }
 14      {
 15          System.out.println ( "parent configuration code blocks" );
 16      }
 . 17      public Fu () {
 18 is         System.out.println ( "parent class constructor" );
 . 19      }
 20 is  }
 21 is  
22 is  class Zi the extends Fu {
 23 is      static {
 24          System.out.println ( "static block of code subclass" );
 25      }
 26 is      public Zi ( ) {
 27          System.out.println ( "subclass constructor" );
 28      }
 29      {
 30          System.out.println ( "Code block construction of subclasses" );
 31      }
 32 }

According to this operation example view order: initialization for the parent class, then the subclass initialization, static code region in the process of completion of the static region, it was first completed before the other code execution

Thus it can be obtained, as a result of running this code

Static code block parent class
subclasses the static code block
parent class code block configured
parent class constructor
subclass configured block
subclass constructors

Guess you like

Origin www.cnblogs.com/haoyujun135/p/11328491.html