A class can use static blocks of code that are not contained in any method body. When a class is loaded, a static block of code is executed and executed only once. The actions that cause the class to be loaded include: using the static properties or methods of any class, the object of the new class (declaring the object of the class does not cause a static block of code to be executed). Static code blocks are often used for initialization of class properties. Take a look at the following tests:
Class person{Public Person () { System.out.println (' 1.public person () '); } static { System.out.println ("The 2.Person class is called!");} } public class teststaticdemo5{ static { System.out.println ("3.teststaticdemo5 class is called!"); } public static void Main (String args[]) { System.out.println ("4. The program starts executing! "); New person (); New person (); }}
Save the above code as a file Teststaticdemo5.java. "Javac Teststaticdemo5.java" is compiled and executes "Java TestStaticDemo5", printed as follows:
The static code block of the 3.teststaticdemo5 class is called!
4. The program starts to execute!
The static code block of the 2.Person class is called!
1.public person ()
1.public person ()
Java static code blocks, literacy stickers