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才对啊!
{ 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才对啊!
也就是 说你前面的对象 对 属性做的修改 不会 后面的有影响。呵呵
改成 static int y = 0 就可以得到你说的结果。
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