The initialization sequence and time of static members in Java are always confused. I verified it with the following code today, and I feel a lot of problems have suddenly become apparent.
// StaticInitialize.java// To test some details of the// initialization of static fields.import java.util.*;class RandFields {static private Random rand = new Random();private static int a = statint();private int b = normalint();static private int statint() {int i = rand.nextInt(50);System.out.println("static initialization " + i);return i;}private int normalint() {int i = rand.nextInt(50);System.out.println("normal initialization " + i);return i;}public RandFields() {System.out.println("this is constructor");System.out.println("static int a = " + a + ", int b = " + b);}public static void print() {System.out.println("This is static method print");}}public class StaticInitialize {public static void main(String[] args) {RandFields.print();RandFields rand1 = new RandFields();RandFields rand2 = new RandFields();}}
The running result is as follows:
It can be seen that if you simply use static methods in the class, the constructor will not be called. Let's look at the following verification:
// StaticInitialize.java// To test some details of the// initialization of static fields.import java.util.*;class RandFields {static private Random rand = new Random();private static int a;// = statint(); //Change hereprivate int b = normalint();static private int statint() {int i = rand.nextInt(50);System.out.println("static initialization " + i);return i;}private int normalint() {int i = rand.nextInt(50);System.out.println("normal initialization ");return i;}public RandFields() {System.out.println("this is constructor");a = rand.nextInt(50); //Change hereSystem.out.println("static int a = " + a + ", int b = " + b);}public static void print() {System.out.println("This is static method print");System.out.println("a = " + a);//Change here}}public class StaticInitialize {public static void main(String[] args) {RandFields.print();RandFields rand1 = new RandFields();RandFields rand2 = new RandFields();}}
The running result is as follows:
At this time, static members are initialized in the constructor, and different values are generated each time. However, all objects share a static member.