Add some of your own code blocks to execute after the initialization of the variables, also conform to the Java programming idea----static construction code block > variable Initialization >
NormalBuilding code Blocks
During the programming process, we may encounter the following form of program:
public class Test { { //// }}
This form of the program segment we call this code block, the so-called code block is to use curly braces ({}) to encapsulate multiple lines of code together to form a separate data body for the implementation of a specific algorithm. Generally speaking, a block of code cannot be run alone, it must have a running body. The code blocks in Java are divided into four main types:
One, ordinary code block
Common code blocks are the most commonly used and most common, which is the code snippet enclosed in {} after the method name. An ordinary block of code cannot exist alone, it must be immediately following the method name. It must also be called using the method name.
public class Test {public void Test () { System.out.println ("Plain code block");} }
Second, static code block
When we think of static, static blocks of code, which are statically decorated with {}, are the main purpose of initializing static properties.
public class Test { static{ System.out.println ("Static code Block");} }
Third, synchronous code block
Use the Synchronized keyword to decorate and use a code fragment enclosed in "{}", which means that only one thread can enter the method block at a time and is a multithreaded protection mechanism.
Iv. Building blocks of code
A block of code that is directly defined in a class without any modifiers, prefixes, and suffixes is constructed. We understand that a class must have at least one constructor, and the constructor is called when the object is generated. Constructing code blocks and constructors is also called when generating an object, so when is the construction code called? How is it called? Look at the following code:
public class Test { /** * Constructs code * /{System.out.println ("Execute Construction code block ..."); /** * No parameter constructor */public Test () { System.out.println ("Execute parameterless constructor ..."); /** * Parameter Constructor * @param ID ID */public Test (String id) { System.out.println ("execute the parameter constructor ..."); }}
The above defines a very simple class that contains an parameterless constructor, a parameter constructor, and a block of code, while also mentioning that the code block is not capable of running independently, and that he must have a carrier that can be hosted, so how does the compiler handle building blocks of code? The compiler inserts blocks of code in their order (if there are multiple blocks of code) into the front of all constructors, which ensures that all construction blocks are executed regardless of which constructor is called. The above code is equivalent to the following form:
public class Test { /** * No parameter constructor */public Test () { System.out.println ("Execute Construction code block ..."); System.out.println ("Execute parameterless constructor ..."); /** * Parameter Constructor * @param ID ID */public Test (String id) { System.out.println ("Execute construct code block ...") ); System.out.println ("execute a parameter constructor ...");}
Run results
public static void Main (string[] args) { new Test (); System.out.println ("----------------"); New Test ("1"); ------------Output: Execute Construction code block ... Execute the parameterless constructor ...----------------execute the construction code block ... Execute a parameter constructor ...
From the running results above, we can see that the construction code is always executed first in the new object, and then the constructor is executed, but it is important to note that the construction code is not run before the constructor, it is executed by the constructor function. It is because of these characteristics that a block of code is constructed that it is often used in the following scenarios:
1. Initialize instance variables
If there are several constructors in a class, the constructors need to initialize the instance variables, and if we instantiate them directly in the constructor, there will be a lot of duplicate code, cumbersome and poor readability. Here we can make full use of the construction code block to implement. This is an attribute that leverages the compiler to add construction code blocks to each constructor.
2. Initializing the instance environment
An object must exist in the appropriate scenario, and if there is no appropriate scene, you will need to create the scene when you create the object. We can create this scenario by building blocks of code, especially when the scene is created more complex. The construction code is executed before the constructor function.
The above two common scenes take full advantage of the characteristics of the construction code block, can solve the problem that the constructor is difficult to solve when the object is instantiated, and the construction code can not only reduce the amount of code, but also enhance the readability of the program. In particular, when the creation of an object is complex and requires some complex logic, it is not recommended to implement logic in the constructor, since we advocate that the constructors are as straightforward as possible, so we can encapsulate these logical implementations using construction code.
V. Static code blocks, construction code blocks, constructor execution order
From the word surface we can see the difference between them. Static code block, static, whose action level is class, constructs code block, constructor, construct, its action level is object.
1, static code block, it is executed as the class is loaded, as long as the class is loaded will be executed, and will only be loaded once, mainly used to initialize the class.
2. Constructs a block of code that executes once when an object is created and takes precedence over the constructor, primarily for initializing content and initializing the instance environment for different object commonalities.
3, constructors, each time an object is created, it is executed once. At the same time the constructor is initialized for a particular object, and the construction code is initialized for all objects, with different areas of action.
From the above analysis, the three of them should be executed in the following order: Static code block > construct code block > constructor.
public class Test { /** * Static code block * /static{System.out.println ("Execute Static code block ..."); /** * Construct code block * /{System.out.println ("Execute Construction code block ..."); /** * No parameter constructor */public Test () { System.out.println ("Execute parameterless constructor ..."); /** * Parameter Constructor * @param ID */ public Test (String id) { System.out.println ("execute the Parameter constructor ..."); Public static void Main (string[] args) { System.out.println ("----------------------"); New Test (); System.out.println ("----------------------"); New Test ("1");} } -----------Output: Executing a static block of code ...----------------------executing the construction code block ... Execute the parameterless constructor ...----------------------execute the construction code block ... Execute a parameter constructor ...
Vi. variables (fields) initialize static code blocks, construct code blocks, execute order of constructors
Class Soap {
Private String S;
Soap () {
System.out.println ("Soap ()");
s = new String ("constructed");
}
Public String toString () {
return s;
}
}
public class Test {
Private soap Soap=new soap ();
/**
* Static code block
*/
static{
System.out.println ("Execute Static code block ...");
}
/**
* Construct code blocks
*/
{
SYSTEM.OUT.PRINTLN ("Execute Construction code block ...");
}
/**
* No parameter constructor
*/
Public Test () {
System.out.println ("Execute parameterless constructor ...");
}
/**
* Parametric constructors
* @param ID
*/
Public Test (String ID) {
System.out.println ("execute a parameter constructor ...");
}
public static void Main (string[] args) {
System.out.println ("----------------------");
New Test ();
System.out.println ("----------------------");
New Test ("1");
}
}
Output
Execute static code block ...
----------------------
Soap ()
Execute construct code block ...
Execute parameterless constructor ...
----------------------
Soap ()
Execute construct code block ...
Execute a parameter constructor ...
Java Improved-----code block