关于static问题的分析

来源:互联网 发布:格瓦拉网络购票 编辑:程序博客网 时间:2024/06/06 13:14
package com.bzu.csh;


/**
 * 类加载器加载.class文件---->初始化static声明,并不赋值------>调用类----->static声明赋值由上到下
 * 程序开始运行,首先执行main方法,执行main方法第一条语句,调用Singleton类的静态方法,
 * 这里调用Singleton类的静态方法就是主动使用Singleton类
 * 。所以开始加载Singleton类。在加载Singleton类的过程中,首先对静态变量赋值为默认值, Singleton=null counter1 =
 * 0 Counter2 = 0
 * */
class Singleton {
private static Singleton singleton = new Singleton();
public static int counter1;
public static int counter2 = 33;


private Singleton() {
counter1++;
counter2++;
System.out
.println("构造方法" + counter1 + ":" + counter2 + ":" + singleton);// 1:1:null
}


public static Singleton getInstance() {
return singleton;
}
}


public class Test {
public static void main(String[] args) {
Singleton singleton = Singleton.getInstance();//
System.out.println("counter1 = " + singleton.counter1);
System.out.println("counter2 = " + singleton.counter2); // counter1 = 1
// counter2 = 33
}
}
0 0
原创粉丝点击