Java中的静态成员初始化的顺序、时间总是存在着一些迷惑。今天用以下代码验证了一下,感觉好多问题豁然贯通。
// 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(); } }以下是运行结果:
可见,如果单纯使用类中的静态方法,是不会调用构造器的。再看以下的验证:
// 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 here 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 "); return i; } public RandFields() { System.out.println("this is constructor"); a = rand.nextInt(50); //Change here System.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(); } }以下是运行结果:
此时的静态成员在构造器中初始化,则每次会有不同的值,但是,所有的对象是共享一个静态成员的。
原文:http://blog.csdn.net/pdcxs007/article/details/18628177