Article Author: Tyan
Blog: noahsnail.com | CSDN | Jane book 1. Initialization in Java
One difference between Java and C + + is that Java has not only constructors, but also an "initialization block" (initialization blocks) concept. Initialization blocks in Java are implicitly executed when a Java object is created, and are executed before the constructor. 2. Static initialization
Define
static {
...
}
Static initialization block execution takes precedence over non-static initialization blocks, executes once when the object is loaded into the JVM, and can only initialize class member variables, which are static-decorated data members. 3. Non-static initialization
Define
{
...
}
Non-static initialization blocks are executed once for each object's generation, and can initialize instance variables of the class. Non-static initialization blocks are executed before the constructor. 4. Demo Example
Class Test {
static {
System.out.println ("Run static initailization block.");
}
{
System.out.println ("Run nonstatic initailization block.");
}
Public test () {
System.out.println ("Run Test constructor.");
}
public static void Main (string[] args) {
Test t = new Test ();
}
Result
Run static initailization block.
Run nonstatic initailization block.
Run Test Constructor.
5. Summary
In a way, the initialization block is a complement to the constructor, and the initialization block is always executed before the constructor. The initialization block is a piece of code that is executed in a fixed format and cannot accept any arguments. The initialization block therefore initializes the same initialization process for all objects of the same class. If you have a section of initialization code that is exactly the same for all objects, and you do not need to accept any arguments, you can extract the initialization code into the initialization block. The reuse of initialization code can be better improved by extracting the same code from multiple constructors into the initialization block. Static initialization blocks are class-dependent, and the system executes static initialization blocks when the class is loaded, rather than when the object is created, so the static initialization block is always executed before the non-static initialization block. Purpose: For example, when JNI calls, the dynamic link library needs to be loaded and can be loaded in a static code block.