Understanding of java code blocks

package code block;
class mmm{
	// build block
	{
		System.out.println("mmm 1 normal block");//Execute once for each instantiation, and before the constructor.
	}
	//static code block
	static {
		System.out.println("mmm 2 static");//It takes precedence over constructors and normal blocks and is executed only once
	}
	//Construction method
	public mmm() {
		System.out.println("mmm 3 constructor");
	}
}
public class block {
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		{
			int x = 1;
			System.out.println("Main class 1 ordinary block "+x);//Ordinary block in the main class
		}
		int x = 2;
		System.out.println("Main class 3 mian method "+x);
		new mmm();
		new mmm();
		new mmm();
	}
	{
		System.out.println("Main class 4 ordinary blocks");//Ordinary blocks outside main in the main class will not be called
	}
	//Main class static code block
	static {
		System.out.println("Main class 2 static");//Ordinary blocks will be called outside main in the main class, and before the main method
	}
	

}

  Output result:

1 main class 2 static 
2 main class 1 common block 1
 3 main class 3 mian method 2
 4 mmm 2 static 
5 mmm 1 common block
 6 mmm 3 construction method
 7 mmm 1 common block
 8 mmm 3 construction method
 9 mmm 1 common block
 10 mmm 3 Construction methods

Summarize:

In a class, the construction block will be executed each time it is instantiated, and it takes precedence over the construction method. The static construction block, also known as the static code block, takes precedence over the construction block call, and is called only once, and is generally used to initialize static properties.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324905156&siteId=291194637