public class Singleton {
private static Singleton obj = new Singleton();
private static int counter1;
private static int counter2=0;
private Singleton(){
counter1++;
counter2++;
}
public static Singleton getSingleton(){
return obj;
}
public static void main(String[] args) {
Singleton.getSingleton();
System.out.println(counter1);
System.out.println(counter2); }
}结果为什么是:
               1
             0请求达人详解

解决方案 »

  1.   

    counter1++; 
    你这样输出当然是1了,那你在输出就是2了。
    这是自加的运算符,先赋值再加1.counter2++;
    这个和上面是一样的啊。
      

  2.   


    public class Singleton {
    private static Singleton obj = new Singleton();
    private static int counter1;
    private static int counter2 = 0; private Singleton() {
    counter1++;
    counter2++;
    } public static Singleton getSingleton() {
    return obj;
    } public static void main(String[] args) {
    Singleton.getSingleton();
    System.out.println(counter1);
    System.out.println(counter2); }
    }
    首先执行第一行红的代码,把counter1和counter2都变成1
    然后再执行第2个红行,吧counter2变成了0呵呵,这是我自己看的,也没有什么理论依据...
      

  3.   

    晕,Java代码里面还不能用红字标识啊,那就是用包围的代码了
      

  4.   

    debug 一下你就清楚了
    先执行
    private Singleton(){ 
    counter1++; 
    counter2++; 

    再执行
    private static int counter2=0; 
    结果当然是 1 0如果改成
    private static int counter1;
    private static int counter2 = 0;
    private static Singleton obj = new Singleton();
    结果就是
    1
    1
      

  5.   

    本人的看法:private static Singleton obj = new Singleton();  此时 count1=1,count2=1 private static int counter1;此时 count=1,count2=1private static int counter2=0;些时 counter2 被重新赋值 count1=1,counter2=0