Common code blocks:
method, limit the variable life cycle, release early, and improve memory utilization.
To construct a code block:
occurs outside of a method in a class, the construction block is called when the object is created, each The second call construct is executed and executed before the method is constructed .
Static code block:
method, with static modification, to initialize the class, execute at load time, and execute only once.
Synchronizing code blocks:
using synchronized () {} Wrapped blocks of code, in a multithreaded environment, the read and write operation of the shared data is mutually exclusive, otherwise it will result in inconsistencies in the data. The synchronization code block needs to be written in the method.
Example 1:
class Student { static { System.out.println ("Student code block"); } { System.out.println ("Student Construction code block"); } Public Student () { System.out.println ("Student constructor method");} }
class demo2_student { static { System.out.println ("demo2_student code block"); } publicstaticvoid main (string[] args) { System.out.println ("I am Main method "); New Student (); New Student (); }}
execution Flow: First you need to load the class Demo2_student and execute the static code block after loading. The main method is then executed. Creating a Student object requires loading the class first, and then executing a static block of code when the class is loaded. Then, before the new object executes the construction code block, the paparazzi method is executed.
Example 2:
class test2_extends { publicstaticvoid main (string[] args) { New Zi (); }}
class Fu { static {System.out.println ( "Static code block Fu" Construction code block Fu " public Fu () {System.out.println ( "Construction method Fu"
class extends Fu { static { System.out.println ("Static code block Zi"); } { System.out.println ("construct code block Zi"); } Public Zi () { System.out.println ("Construction method Zi");} }
Execution process:
1,JVM called the Main method, the main input stack
2, encountering Zi z = new Zi (), the Fu.class and Zi.class are loaded into memory first, and then the object is created, when Fu.class loads the static code block of the memory parent class along with the Fu.class, when zi.class loads into memory, the subclass's static Code blocks are loaded along with Zi.class. First output static code block Fu, second output static block of code Zi
3, and then go to the constructor of the Zi class, because Java is hierarchical initialized, first initializes the parent class, and then initializes the subclass, so the parent class is first constructed, but when the parent class is constructed, it is found that the parent class has a construction code block, and the construction code block is the third output constructs the code block Fu, Fourth output construction Method Fu
4,fu class initialization, subclass initialization, fifth output is the construction code block Zi, construction method Zi
Java code block