写出以下程序的运行结果。
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); // 2
System.out.println("st.y=" + st.y); // 1
st=new StaticTest();
System.out.println("st.y=" + st.y); // 为何这个地方 y为 1 而不是2 呢?
}
static { x++;}
}帮忙解释下 为何第二次new 对象时 y的值是在0基础上+1,而不是1的基础上加1.
谢谢!
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); // 2
System.out.println("st.y=" + st.y); // 1
st=new StaticTest();
System.out.println("st.y=" + st.y); // 为何这个地方 y为 1 而不是2 呢?
}
static { x++;}
}帮忙解释下 为何第二次new 对象时 y的值是在0基础上+1,而不是1的基础上加1.
谢谢!
int y y变量是属于每个StaticTest对象的成员变量,对于每个对象来说y初始都是0的,所以你new出来以后都是1
而y是成员属性,每个对象有一个自己的y.再创建对象时,先默认初始化为0,执行完构造方法后,变成1。
你第二次new 时是产生了一个新的对象,这个对象的"y"和上一个对象的"y"是不一样的,属于两个对象。