本帖最后由 wnmmp 于 2014-8-13 00:52 编辑
这是我在基础测试遇到的一题,首先没有private时,直接可以new两个Single对象,打印显示他们的地址值不一样:
- public class Test5 {
- public static void main(String[] args) {
- System.out.println(new Single());
- System.out.println(new Single());
- }
- }
- class Single
- {
- Single(){}
- private static Single s = null;
- public static Single getInstance()
- {
- if(s==null)
- s = new Single();
- return s;
- }
- }
- /*结果如下:
- com.itheima.Single@1c80b01
- com.itheima.Single@4aa0ce
- * */
复制代码
当有private时,如果new的话直接报错,利用getInstance获取两次都是同一个对象,地址值一样:
- public class Test5 {
- public static void main(String[] args) {
- System.out.println(Single.getInstance());
- System.out.println(Single.getInstance());
- }
- }
- class Single
- {
- private Single(){}
- private static Single s = null;
- public static Single getInstance()
- {
- if(s==null)
- s = new Single();
- return s;
- }
- }
- /*结果如下:
- com.itheima.Single@290fbc
- com.itheima.Single@290fbc
- * */
复制代码
|