日期:2014-05-20  浏览次数:20713 次

java所有程序员都可能犯错误的一道题!!!
public class Singleton {

  public static Singleton singleton=new Singleton();
  public static int a;
  public static int b=0;
  public static int c=2;
   
   
  private Singleton()
  {
super();
a++;
b++;
  c++;
  }
  public static Singleton getInstance()
  {
return singleton;
  }
   
  public static void main(String [] args)
  {
Singleton sl=Singleton.getInstance();
System.out.println("a="+sl.a);
System.out.println("b="+sl.b);
System.out.println("c="+sl.c);
  }
}

找牛人解决以上一道题!在线等待回答



------解决方案--------------------
又是这个问题
要知道,定义和赋值是两个语句
int a = 0; 相当于 int a; a = 0;两条语句,int a是定义,用于分配内存,即方法栈生成的时候,在数据区的a的相对地址里留出一定的空间(int长度),作为a的内存空间,a = 0;是赋值语句,在语句被执行的时候的,往a的内存地址保存一个0,所以定义语句是在栈生成的时候就决定,赋值语句是在程序执行的时候决定的。而对于成员变量,int定义的时候,系统会自动初始化变量为0

//所以
public static Singleton singleton=new Singleton(); //此时a,b,c被定义,在栈中分配空间,然后出初始化为0,然后掉用构造方法,分别执行相应的赋值语句
public static int a;
public static int b=0; //然后 这里 相当于 int b; b=0; 即b=0语句被执行,所以b有重新变为0
public static int c=2; //同理,这里把c又变成2


------解决方案--------------------
看一下程序都干了些什么就清楚了呗。
PS:在下也是刚接触字节码不久,只能给点简单的说明:
第一种情况:
Java code

class Test9 {
    public static Test9 singleton = new Test9();
    public static int a;
    public static int b = 0;
    public static int c = 2;
    //public static Test9 singleton = new Test9();
……
}

对应字节码:
public class com.codetest.test.Test9 {
  public static com.codetest.test.Test9 singleton;

  public static int a;

  public static int b;

  public static int c;

  static {};
    Code:
       0: new           #17                 // class com/codetest/test/Test9
       3: dup           
       4: invokespecial #18                 // Method "<init>":()V      // 这里应该是调用构造函数
       7: putstatic     #5                  // Field singleton:Lcom/codetest/test/Test9;
      10: iconst_0      
      11: putstatic     #3                  // Field b:I         // 这里对应 b = 0
      14: iconst_2      
      15: putstatic     #4                  // Field c:I         // 这里对应 c = 2
      18: return        
}