0

我有以下代码,我可以在其中static counter field跟踪Parent创建了多少对象。当我创建子类的实例时,计数器parent也会增加,这是我不想发生的。有什么帮助吗?

这是代码

class Parent1 {
    private String name;
    private int id;
    public static int count=0;

    public Parent1(String name, int id){
        this.name=name;
        this.id=id;
        count++;
    }
}

class Child1 extends Parent1{
    private int age;

    public Child1(String name, int id, int age){
        super(name, id);
        this.age=age;
    }
}
public class App {
    public static void main(String[] args){
    Parent1 par= new Parent1("aa",5);
    Parent1 par2=new Parent1("bb",10);
    System.out.println(Parent1.count);
    Child1 chi1= new Child1("aa",5,4);
    Child1 chi2=new Child1("bb",5,10);
    System.out.println(Child1.count);
    }
}

The output is 
2
4
4

4 回答 4

4

Parent1的构造函数中:

if (getClass() == Parent1.class)  // <--
    count++; 
于 2013-09-25T21:12:47.657 回答
3

做这个:

class Parent1 {
    private String name;
    private int id;
    public static int count=0;

    public Parent1(String name, int id) {
        this(name, id, true);
    } 

    protected Parent1(String name, int id, boolean incrementCount){
        this.name=name;
        this.id=id;
        if( incrementCount )
            count++;
    }
}

class Child1 extends Parent1{
    private int age;

    public Child1(String name, int id, int age){
        super(name, id, false);
        this.age=age;
    }
}

//....

Parent1 par= new Parent1("aa",5);
Parent1 par2=new Parent1("bb",10);
于 2013-09-25T21:14:25.403 回答
0

添加count--;到子类构造函数。

于 2013-09-25T21:16:06.193 回答
0

您可以使用以下模式来解决问题。

class Parent1 {
    private String name;
    private int id;
    public static int count=0;

    public Parent1(String name, int id){
        this(name,id,true);
        count++;
    }
    public Parent1(String name, int id,boolean noIncrement){
        this.name=name;
        this.id=id;
    }
}

class Child1 extends Parent1{
    private int age;

    public Child1(String name, int id, int age){
        super(name, id,true);
        this.age=age;
    }
}
public class App {
    public static void main(String[] args){
    Parent1 par= new Parent1("aa",5);
    Parent1 par2=new Parent1("bb",10);
    System.out.println(Parent1.count);
    Child1 chi1= new Child1("aa",5,4);
    Child1 chi2=new Child1("bb",5,10);
    System.out.println(Child1.count);
    }
}
于 2013-09-25T21:19:08.540 回答