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.
Task
Little friends, do a practice to deepen your understanding of static initialization blocks!
In the editor, the variables are initialized with the constructor method, initialization block, and static initialization block, respectively.
Complete the code in section 8, 20, and line
Reference running results:
Public classHelloWorld {String name;//declaring variable nameString sex;//Declaring variables Sex Static intAge//declaring a static variable age//Construction Method PublicHelloWorld () {System.out.println ("Initialize name by construction method"); Name= "Tom"; } //Initialize block{System.out.println ("Initialize sex by initializing blocks"); Sex= "Male"; } //Static initialization blocks Static{System.out.println ("Initialize age by static initialization block"); Age= 20; } Public voidShow () {System.out.println ("Name:" + name + ", Gender:" + Sex + ", Age:" +Age ); } Public Static voidMain (string[] args) {//Creating ObjectsHelloWorld Hello =NewHelloWorld (); //call the Show method of an objecthello.show (); }}
Static initialization block used in Java