How to count the number of all instances of a class and their respective subclasses?

2

I have a class A , where A extends in B and C . I have an instance counter in A .

public Class A {

...

   private int nInstancias = 0;

   ...

   public A(){
      nInstancias+=1;
      ...
   }

   ...

   public int getnInstancias() {
       return nInstancias;
   }

   ...

}

However, whenever I print nInstancias with its getNInstancias , it always returns 0.

What am I doing wrong and how can I increase n Instances always instantiate A or any subclass of A ?

Is it also necessary to change the nInstances in the subclass constructor?

    
asked by anonymous 31.03.2018 / 17:47

1 answer

3

Try changing the variable to static, so its value will depend on the instance to which it is bound:

private static int nInstancias = 0;

and within the A constructor:

public A(){
   nInstancias++;
   ...
}

Note: Since the other classes extend from A, the counter will increment each time an instance of B and C is created. See the test:

public  class ClasseA {

    private static int instances = 0;

    public ClasseA() {
        instances++;
    }

    public static int getNumberInstances(){
        return instances;
    }

    public static void main(String[] args) {

        System.out.println("Instanciando ClasseA...");
        ClasseA a = new ClasseA();
        System.out.println("No. de instancias: " + ClasseA.getNumberInstances());

        System.out.println("Instanciando ClasseB...");
        ClasseB b = new ClasseB();
        System.out.println("No. de instancias: " + ClasseA.getNumberInstances());

        System.out.println("Instanciando ClasseC...");
        ClasseC c = new ClasseC();
        System.out.println("No. de instancias: " + ClasseA.getNumberInstances());
    }
}


class ClasseB extends ClasseA {

}

class ClasseC extends ClasseA{

}

Result:

Instanciando ClasseA...
No. de instancias: 1
Instanciando ClasseB...
No. de instancias: 2
Instanciando ClasseC...
No. de instancias: 3

Running: link

Reference:

31.03.2018 / 17:52