<> Code block

The code block is declared in the class , It is similar to a method body without a name ( Code block ), Code block is divided into instance block and static block .

Instance block : Called automatically every time an object is created

{

// Anything that is grammatically correct java code

}

Static block : Class is called automatically when it is loaded , Only once , It has nothing to do with whether or not to create an object .

static{

​ // Anything that is grammatically correct java code

}
public class Demo { static int num = 10; { System.out.println(" Instance block "); } static{
System.out.println(" Static block "); } } public static void main(String[] args) { System.
out.println(Demo.num); System.out.println(Demo.num); System.out.println(Demo.num
); } /* result : Static block 10 10 10 */ public static void main(String[] args) { new Demo();
// Load class first Then create the object new Demo(); }/* result : Static block Instance block Instance block */
be careful :

JAVA The order of initialization in :

Load class ;

Static variable initialization

Static code block ;【 It can only schedule static , Non static cannot be scheduled 】

Member variable

Construct code block

Construction method

Common code block

Technology
Daily Recommendation
views 255
views 221
views 210