A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 杨志罡 黑马帝   /  2011-8-7 22:41  /  1837 人查看  /  3 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

[code=java]package com.yang.test1;

public class MyTest {

        public static void main(String[] args) {
                Singleton singleton = Singleton.getInstance();
               
                System.out.println(singleton.counter1);
               
                System.out.println(singleton.counter2);
        }
       
}
class Singleton{
       
       
        //情况1private static Singleton singleton = new Singleton();
        public  static int counter1;
       
        public  static int counter2 = 0;
        //情况2private static Singleton singleton = new Singleton();
         //打开其中一种情况运行
        private Singleton() {
                counter1++;
                counter2++;
        }
       
        public static Singleton getInstance() {
                return singleton;
        }
}[/code]

3 个回复

倒序浏览
黑马网友  发表于 2011-8-8 01:04:38
沙发
我就说一下我debug的情况//情况1private static Singleton singleton = new Singleton();
main方法开始执行Singleton singleton = Singleton.getInstance(); 的时候就开始加载Singleton这个类static修饰的字段和方法都开始产生了 此时new Singleton(); count1=1 count2=1,然后执行静态public  static int counter1; 因为有值了就不用初始化,然后执行public  static int counter2 = 0; 就将count2=0
//情况2private static Singleton singleton = new Singleton(); 一加载这个类的时候先public  static int counter1; public  static int counter2 = 0;  此时count1 和count2都为0  然后就执private static Singleton singleton = new Singleton(); 对其自增   就全部为1
主要是static先后顺序的问题public   int counter1 ;public  int counter2 = 0;你去掉static不管private static Singleton singleton = new Singleton(); 在哪都是执行了一次
你在构造方法中添加了这句话System.out.println("counter1="+counter1+",counter2="+counter2);会发现有他们都曾经为1过

评分

参与人数 1技术分 +2 收起 理由
詹季春 + 2 没错、是这么个道理

查看全部评分

回复 使用道具 举报
黑马网友  发表于 2011-8-8 02:07:54
藤椅
无论有多少个实例对象,首先是静态代码块,静态变量被执行且被执行一次,然后是自段,然后是父类构造方法,再到自己构造方法
回复 使用道具 举报
黑马网友  发表于 2011-8-9 22:39:24
板凳
这么精辟的问题 怎么不给楼主加分
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马