Initializing blocks
The initialization block is a member of four kinds (properties, methods, constructors) that can appear in Java classes. There can be more than one initialization block in a class, and there is an order between multiple initialization blocks: The previous initialization block executes first, followed by the initialization block.
If the initialization block is decorated with static, it becomes a static initialization block. The initialization block can protect any execution statements, including defining variables, conditional branching statements, looping statements, and so on.
The initialization block has no name and cannot be invoked, and it is implicitly executed when an object is created. Initialization is performed quickly before the constructor. Initialization blocks and attribute declarations in a class can be assumed to be initialization code, and they are executed in the same order as they are arranged in the program. For example:
The public class inittest{
//executes first because the arrangement property of the program is preceded by a = 9
{
a=6
}
In the execution
int a = 9;
Public Inittest () {
int = 12;//Second Execution
}
}
Initializing blocks and constructors
In a way, the initialization block is a supplement to the builder. Unlike a constructor, it is a fixed piece of code that does not accept any arguments. If the code is initialized in more than one constructor in a class and does not accept parameters, it can be extracted into the initialization block so that the code looks more concise.
Similar to the constructor, when creating a Java object, it executes the initialization block of the parent class, the constructor of the parent class, and then the initialization block of this class, the constructor for this class. Static initialization block
If the initialization block that is decorated with static is a static initialization block. It executes when the class is loaded, not when the object is created. Non-static members cannot be accessed in static initialization blocks, which is consistent with static methods that cannot invoke non-static methods and members.
Initialization of static initialization blocks and static properties is initialization code, and they are initialized in the same order as they are arranged in the program.