清钟长鸣 2015-11-15 07:51 采纳率: 40%
浏览 1863
已采纳

java这道题能帮我解答下么?最好能每行注释一下。麻烦各位大神

public class StaticTest {
static int x=1; int y;
StaticTest(){ y++; }

public static void main(String args[ ]){

StaticTest st=new StaticTest();

System.out.println("x=" + x);
System.out.println("st.y=" + st.y);

st=new StaticTest();

System.out.println("st.y=" + st.y);

}

static { x++;}

}

  • 写回答

3条回答 默认 最新

  • Evankaka 博客专家认证 2015-11-15 08:50
    关注
     public class StaticTest {
    static int x=1;//静态变量,类加载时执行,只会执行一次
    int y; //保存成员变量,没有赋值,默认为0
    StaticTest(){ y++; }//构造方法
    
    public static void main(String args[ ]){//main函数,程序执行入口
    
    StaticTest st=new StaticTest();//这里实例化前执行加载,所以x=2.然后执行构造函数y=1
    
    System.out.println("x=" + x);//x=2
    System.out.println("st.y=" + st.y);//y=1
    
    st=new StaticTest();//新的类,但是类加载只执行一次,所以x=2.同进,执行构造函数y=1
    
    System.out.println("st.y=" + st.y);//y=1
    
    }
    
    static { x++;}//静态代码端,类加载时执行
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?