The code block in 4 in Java is summarized as follows:
* Add static code block, write a pair of {} in the class to construct a block of code, in the method write a pair of {} is a common code block,
* There is also a code block in Java that is a synchronous code block, commonly used in multi-threading, synchronized keyword,
* Synchronization code block format is: synchronized (Synchronization object) {}
* Static code blocks are executed before the construction code block before the construction method
* Static code blocks are preceded by the normal code block before the construction method executes
* Construct code blocks and normal code blocks in the order of the program logical execution
Package face question; class Helloa{public Helloa () {System.out.println ("constructor method A");} Code blocks {}, defined directly in the class without the static keyword, are called construction blocks//This is the construction code block, and when the new object is constructed, the code block first constructs the method to execute {System.out.println ("I ' M A class");} A block of code declared with the static keyword is called a static block of code, the primary purpose of which is to initialize the static property//static block takes precedence over the execution of the main method, and the static block takes precedence over the execution of the construction method and executes only once! Static{system.out.println ("Static A");}} Synchronous code blocks are mainly present in multiple threads. public class Hellob extends Helloa{public Hellob () {//super ();//default omitted for this statement System.out.println ("Construction Method B");} Constructs a code block {System.out.println ("I ' M B class");} Static code block STATIC{SYSTEM.OUT.PRINTLN ("Static B");} public static void Main (string[] args) {//The {} that appears directly in a method is called a plain code block//plain code block {System.out.println ("Normal code block 1 in the Main method");} New Hellob ();//Common code block {System.out.println ("Normal code block 2" in Main method);}}}
Output
Static A
Static B
Common code block in the Main method 1
I ' M A class
Construction Method A
I ' M B class
Construction Method B
Common code block in the Main method 2
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Summary of static code blocks, construction code blocks, common code blocks, and synchronous code blocks in Java