Code block
The code block is declared in the class, similar to a method body (code block) without a name, the code block is divided into an instance block and a static block.
Instance block: automatically called every time an object is created
{
//Any java code that conforms to the syntax
}
Static block: automatically called when the class is loaded, only once, regardless of whether the object is created.
static{
//Any grammatical java code
}
public class Demo {
static int num = 10;
{
System.out.println("实例块");
}
static{
System.out.println("静态块");
}
}
public static void main(String[] args) {
System.out.println(Demo.num);
System.out.println(Demo.num);
System.out.println(Demo.num);
}
/*
结果:
静态块
10
10
10
*/
public static void main(String[] args) {
new Demo();// 先加载类 然后创建对象
new Demo();
}/*
结果:
静态块
实例块
实例块
*/
note:
The order of initialization in JAVA:
Load class
Static variable initialization
Static code block; [It can only schedule static, not non-static]
Member variables
Structure code block
Construction method
Normal code block