It is well known that there are two types of initialization blocks in the Java programming language: static initialization block non-static initialization blocks What difference do they have? Let's talk about the difference between static initialization block and non-static initialization block in Java static initialization block definition: static{} Execution priority is higher than non-static initialization block, it will be executed once when the object is loaded into the system, execution is destroyed, it can only initialize class variables, that is, static decorated data Members. It will be executed when the class loads. Execution Priority: 1 non-static initialization block definition: {} If there is a static initialization block, execute the static initialization block and then execute the non-static initialization block, which will be executed once each object is generated, it can initialize the instance variables of the class. A non-static initialization block is run when the constructor executes, before the constructor body code executes. Execution Priority: 2 instances:
1 Packagecom. Demo;2 Public classDemo03 {3 String name;4 intAge ;5 //constructor Initialization priority: 36 PublicDemo03 (String name,intAge ) {7 This. name=name;8 This. age=Age ;9System.out.println ("constructor");Ten } One A //non-static initialization priority: 2 - { -SYSTEM.OUT.PRINTLN ("Non-static initialization"); the } - //Static Initialization priority: 1 - Static{ -SYSTEM.OUT.PRINTLN ("Static Initialization"); + } - + A Public Static voidMain (string[] args) { atDemo03 demo=NewDemo03 ("Zhangs", 1); - } -}
Result: static initialization of non-static initialization constructors
Talking about static initialization block and non-initialization block in Java