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