In Java, data can be assigned by initializing blocks. Such as:
In the declaration of a class, you can include multiple initialization blocks, which are executed sequentially when you create an instance of the class. If you initialize a block with the static adornment, it is called a static initialization block.
It is important to note that static initialization blocks are only executed when the class is loaded and only once, while static initialization blocks can only assign values to static variables and cannot initialize normal member variables .
Let's look at a piece of code:
Operation Result:
by outputting The result, we can see that the static initialization block is executed first when the program is run, then the normal initialization block is executed, and the construction method is finally executed. Because static initialization blocks are only executed once when the class is loaded, static initialization blocks are not executed when the object Hello2 is created again.
Static initialization block