Java堆栈问题

来源:百度知道 编辑:UC知道 时间:2024/05/31 09:12:30
请帮我详解此题的堆栈路线。谢谢

public class test
{
private static test t=new test();
public static int count1;
public static int count2=0;
private test(){
count1++;
count2++;
}
public static test gettest(){
return t;
}
public static void main(String [] args){
test t=test.gettest();
System.out.println("count1: "+t.count1);
System.out.println("count2: "+t.count2);

}
}

上面的执行次序是:

(1) 定义所有的成员变量 不对其赋值(就算是public static int a=13)
(2)执行构造函数
(3) 对static变量定义值赋值

于是count1和count2的值变化是:
(1) 0 0
(2) 1 1
(3) 1 0

你可以通过这个检验:
class test
{
private static test t=new test();
public static int count1;
public static int count2=0;
private test(){
count1++;
count2++;
System.out.println("构造count1:"+count1+" count2:"+count2);
}
public static test gettest(){
return t;
}
public static void main(String [] args){
test t=test.gettest();
System.out.println("count1: "+t.count1);
System.out.println("count2: "+t.count2);

}
}