class StaticTest
{ int y = 0; StaticTest()
{
y++;
System.out.println("count");
} public static void main(String args[])
{
StaticTest st = new StaticTest();// y ==1
System.out.println("st.y=" + st.y);
st = new StaticTest();
System.out.println("st.y=" + st.y);//y ==2
}
}
结果:
count
st.y=1
count
st.y=1
可以看到count被打印了2次,即构造方法执行了2次,如果是这样最后一次打印出st.y应该是=2才对啊!

解决方案 »

  1.   

    你new 了 2次,是2个不同的对象,
    也就是 说你前面的对象 对 属性做的修改 不会 后面的有影响。呵呵
      

  2.   

    每次new int y = 0 都会执行一次
    改成 static int y = 0 就可以得到你说的结果。
      

  3.   

    static int y=0;这样定义y就可以了
      

  4.   

    原代码中StaticTest类的成员变量y是非静态的,所以每次new一个新对象时,每个新对象都有自己的y变量,他们各自的y不会随构造器的多次调用而增加,如果把y变量的修饰符加上static,那么y就变成了公有的类变量,每次调用构造器都会增加y的值将y修改为静态后的代码:class StaticTest {    static int y = 0;    StaticTest() {
            y++;
            System.out.println("count");
        }    public static void main(String args[]) {
            StaticTest st = new StaticTest();// y ==1
            System.out.println("st.y=" + st.y);
            st = new StaticTest();
            System.out.println("st.y=" + st.y);//y ==2
        }
    }作出如上修改后,运行结果:
    count
    st.y=1
    count
    st.y=2