Local code block:
Function: Control the life cycle of variables;
In the program, when we have finished using X, and in the next code, no longer use X, then there is no need to let X in memory space, this case, you can use the local code block, X and its design to the area as a local code block, they do not change in the program execution, Just disappear after the execution is complete.
The form of expression is shown in code as follows:
class Testdemo { publicstaticvoid main (string[] args) { { int x = 9; SYSTEM.OUT.PRINTLN (x); } System.out.println ("Hello world!") ); } }
Construction code block:
Function: It can initialize all objects
exists in: Class.
When a constructor in a class exists in an overloaded form, and there is a common member variable or a common method, it can be initialized by constructing a code block, which reduces the duplication of code!
classperson{PrivateString name; Private intAge ; {System.out.println ("Cons Code Run!"); } person ()//initialize the corresponding object{System.out.println ("Person Now:run!" "); System.out.println ("Eat ————"); } person (String name,intAge ) { This. Name =name; This. age=Age ; System.out.println ( This. Name + "————" + This. Age); System.out.println ("Eat ————"); } }classconscodedemo{ Public Static voidMain (string[] args) {person P=NewPerson (); Person P1=NewPerson ("LiSi", 23); }}
We can see that there is a common code System.out.println ("Eat ————") in the overloaded constructor method in the class person; we can encapsulate him in a block of construction code to initialize the various types.
After optimization, the code is reflected as:
classperson{PrivateString name; Private intAge ; {System.out.println ("Cons Code Run!"); Eat (); } person ()//initialize the corresponding object{System.out.println ("Person Now:run!" "); } person (String name,intAge ) { This. Name =name; This. age=Age ; System.out.println ( This. Name + "————" + This. Age); } Public voideat () {System.out.println ("Eat ————"); } }classconscodedemo{ Public Static voidMain (string[] args) {person P=NewPerson (); Person P1=NewPerson ("LiSi", 23); }}
Static code block:
Characteristics:
1. Executes as the class loads, and only once.
2. Takes precedence over the main function execution.
Function: initializes the class.
When the methods in the class are statically, and the construction method is private, it is not possible for us to instantiate this class, but to let the class add some properties, we can use static blocks of code:
The form of expression is shown in code as follows:
classstaticcode{Static{System.out.println (A); } Public voidShow () {System.out.println ("Hello World!"); }}classstaticcodedemo{Static{System.out.println (B); } Public Static voidMain (string[] args) {NewStaticcode (). Show (); } Static{System.out.println (C); }}
Local code block, construction code block, static code block in Java