[Javase Study Notes]-7.14 static code block
In this section, we look at a special concept, that is, static code blocks.
As we mentioned earlier, a code block is an independent code space. What is a static code block? To put it bluntly,It is a code block modified with the static keyword.
Let's look at an example:
Class StaticBlock {static {System. out. println ("static code block executed");} void myPrint () {System. out. println ("myPrint method execution") ;}} class StaticBlockTest {public static void main (String [] args) {new StaticBlock (). myPrint ();}}Let's take a look at the running results:
From the results, we can see that the myPrint function we called is called and executed, and the static code block has been executed before this function is called.
This is what we want to talk about. A static code block is a special code block. It is modified by the static keyword and has all the static features. The most important thing is that it has a natural and unique feature: as we said earlier,The static code block is loaded with the class, and the static code block is executed with the class loading. As long as the class is loaded, the static code block will be executed only once.
Let's take a look at the following test:
class StaticBlockTest {public static void main(String[] args) {new StaticBlock().myPrint();new StaticBlock().myPrint();}}Result:
We can see that the static code block is executed only once, and our myPrint method is called twice. So when the class is loaded, the static method has been loaded and executed once.
Through the above example, we have clarified the actual function of the static code block:Class initialization.
This is equivalent to the constructor we learned earlier. constructor is used to initialize objects, while static code blocks are used to initialize classes.
Here we may have doubts: Since constructors can be initialized, why should we use static code blocks for initialization? In fact, not all classes can create objects, because some classes may not need to be created. For example, if we define all static members in a class, it makes no sense to create an object.
Let's look at the usage of a static code block. Let's look at the following code:
class StaticBlock{static int num;static{num = 10;num = num * 3;}void myPrint(){System.out.println("num = "+num);}}class StaticBlockTest {public static void main(String[] args) {new StaticBlock().myPrint();}}Let's look at the running result:
From the results, we can see that we have performed multiple operations and assigned values on static variables in the static code block. Therefore, when we need to perform multiple operations on static variables, we can use static code blocks.
However, this is not much used in development and will be used in some underlying framework development.
In this section, we will simply learn this.