1、创建一个Mytest6类和Singleton类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | public class MyTest6 { public static void main(String[] args) { Singleton singleton = Singleton.getInstance(); System.out.println( "counter1:" +Singleton.counter1); System.out.println( "counter2:" +Singleton.counter2); } } class Singleton{ public static int counter1 ; public static int counter2 = 0 ; private static Singleton singleton = new Singleton(); private Singleton(){ counter1 ++; counter2 ++; } public static Singleton getInstance(){ return singleton; } } |
输出结果
1 2 | counter1: 1 counter2: 1 |
2、将counter2成员变量的位置移动到构造函数后面
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | public class MyTest6 { public static void main(String[] args) { Singleton singleton = Singleton.getInstance(); System.out.println( "counter1:" +Singleton.counter1); System.out.println( "counter2:" +Singleton.counter2); } } class Singleton{ public static int counter1 ; private static Singleton singleton = new Singleton(); private Singleton(){ counter1 ++; counter2 ++; System.out.println( "Singleton counter1:" +counter1); System.out.println( "Singleton counter2:" +counter2); } public static int counter2 = 0 ; public static Singleton getInstance(){ return singleton; } } |
输出结果如下:
1 2 3 4 | Singleton counter1: 1 Singleton counter2: 1 counter1: 1 counter2: 0 |
首先Singleton singleton = Singleton.getInstance(); 是调用Singleton类的getInstance(),属于主动调用。Singleton在准备阶段,按照声明的顺序,赋予所有成员变量默认值。在初始化阶段,构造函数里couonter1和counter2的值变为1,但是后面counter2的值又被赋值为0。 所以打印了上面的结果。
上面代码中的构造函数里counter2 ++;
准备阶段的意义:如果没有准备阶段,counter2是没有值的,更不会有++操作
作者:Work Hard Work Smart
出处:http://www.cnblogs.com/linlf03/
欢迎任何形式的转载,未经作者同意,请保留此段声明!
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步