java静态类变量问题

来源:百度知道 编辑:UC知道 时间:2024/07/08 14:33:35
父类如下:
public class Parent {
protected int id;
protected String name;
public static int counter=0;

public Parent() {
counter++;
this.id=counter;
this.name="Unknow";
}
}

子类如下:
public class Child extends Parent {
public Child() {
super();
}
public Child(Child ch) {
counter++;
this.id=counter;
}
public static void main(String[] args) {
Child ch1,ch2;
ch1=new Child();
ch2=new Child(ch1);
System.out.println("there're "+counter+" Person");
System.out.println("ch2.id="+ch2.id);
}
}
为何输出结果是:
there're 3 Person
ch2.id=3
而不是:
there're 2 Person
ch2.id=2.
也就是说,为什么会有3个对象产生,而不是两个?当我在子类中的第二个构造函数中去掉“counter++”语句,就得到了想要的结果,但是,这个时候,语句ch2=new Child(ch1)中,counter在哪里自增了1呢?哪位高手指点一下,谢谢!

在构造子类对象的时候会调用父类的无参构造函数..
因此
ch1=new Child();时会调用父类的的无参构造函数
public Parent() {
counter++;
this.id=counter;
this.name="Unknow";
}
counter进行了加一操作变成了1

ch2=new Child(ch1);时先调用父类无参构造函数
counter又进行了一次加一操作变成了2
然后执行Child(child ch)构造函数本身的内容.
public Child(Child ch) {
counter++;
this.id=counter;
}
此时counter再次加一就成了为3..此时的ch2的id被赋予当前counter的值即3
因此结果是
there're 3 Person
ch2.id=3

这是因为,当执行 ch1=new Child()时,会先执行父类的构造函数,而执行ch2=new Child(ch1)时,还是会执行父类的构造函数,正所谓,“先有父亲,在有儿子”就是这个道理。在创建子类对象的时候,一定会先去创建父类对象,这时,如果提供了构造函数。所以这两个子类对象在构建的时候,都会先去执行父类的构造函数。表达能力有限,不知道你明白了没有

我看是count++被执行了两次,第一次是子类的构造器中,第二次是父类的构造器中