首页 > 其他 > 详细

Java静态成员初始化问题

时间:2014-01-21 23:42:28      阅读:374      评论:0      收藏:0      [点我收藏+]

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();
	}
}
以下是运行结果:

bubuko.com,布布扣

可见,如果单纯使用类中的静态方法,是不会调用构造器的。再看以下的验证:

// 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();
	}
}
以下是运行结果:

bubuko.com,布布扣
此时的静态成员在构造器中初始化,则每次会有不同的值,但是,所有的对象是共享一个静态成员的。

Java静态成员初始化问题

原文:http://blog.csdn.net/pdcxs007/article/details/18628177

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!