Java _ free block (static block and non-static block)

Source: Internet
Author: User

Free blocks in Java are divided into two types:

Static and non-static Blocks

Static block:

  1   Public   class   test {  2   static   int  X = 10 ;   3  ///   static block: the execution time of the static block is when the class file is loaded; the static block is executed only once   4  ///   when multiple static blocks exist, run   5   static  {  6  X + = 5 ;  7  }  8 }

Non-static block:

 
1 Public ClassTest {2//Non-static block: each time an object is initialized, a non-static block is executed. It is executed before the constructor is executed.3//Inheritance relationship: non-static block of the parent class-> constructor of the parent class-> Self-free block-> self-built Function4 {5System. Out. println ("before");6 }7}

Test Demo:

 1   Public  Class  Test {  2   3       Static   Int X = 10 ;  4       //  Static block: the execution time of the static block is only once when the class file is loaded.  5       //  When multiple static blocks exist, they are executed in the order of appearance.  6       Static  {  7 X + = 5 ;  8   }  9       Public   Static   Void  Main (string [] ARGs ){  10           New Test (); 11 System. Out. println (X ); 12   }  13       //  Static Block 14       Static  {  15 X/= 3 ;  16   }  17       Public  Test (){  18 System. Out. println ("constructor" );  19   }  20       // Non-static block: each time an object is initialized, a non-static block is executed. It is executed before the constructor is executed.  21       //  Inheritance relationship: non-static block of the parent class-> constructor of the parent class-> Self-free block-> self-built Function  22   {  23 System. Out. println ("before" );  24   }  25 }

Console output:

 
Before Constructor5

More information: Java free block

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.