Free blocks in Java are divided into two types:
Static blocks and non-static blocks
Static blocks:
Public class Test {2 Static int x = ten; 3 // static block: The execution time of a static block is when the class file is loaded , and the static block executes 4 / more static blocks at a time, in the order of occurrence 5 static{6 x+=5; 7 }8 }
Non-static blocks:
Public class Test {2 // non-static blocks: Each time an object is initialized, a non-static block is executed, and a 3//inheritance relationship is performed before the constructor executes: the constructor of the parent class, the non-static block of the parent class, and its own free block, Own constructor 4 {5 System.out.println ("before"); 6 }7}
Test Demo:
Public classTest {2 3Static intx = 10; 4//static blocks: The execution time of a static block is when the class file is loaded, and the static block executes only once5//multiple static blocks, executed in order of occurrence6Static{ 7 x+=5; 8 } 9 Public Static voidMain (string[] args) {10NewTest ();11System.out.println (x);12 }13//static Block14Static {X/=3;16 }17 PublicTest () {System.out.println ("constructor");19 }20//non-static blocks: Each initialization of an object results in the execution of a non-static block, which executes before the constructor executes21st//Inheritance Relationship: The constructor of the parent class, the non-static block of the parent class, and its own constructor, the free block,22 {System.out.println ("Before");24 }25}
Console output:
before constructor 5
Java Free blocks (static and non-Static) (reprinted)