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

Asked

Viewed 249 times

2

I have a class A, where A extends into B and in C. I have a counter of instances in A.

public Class A {

...

   private int nInstancias = 0;

   ...

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

   ...

   public int getnInstancias() {
       return nInstancias;
   }

   ...

}

However, whenever I print the nInstancias with its getNInstancias, always gives 0.

What I’m doing wrong and how can I increase the instacing nInstancias A or any subclass of A?

It is also necessary to change the nInstances in the subclass builder?

  • private int nInstancias = +; This is not a valid java statement,

  • sorry error. had not repaired @Articuno

1 answer

2


Try to change the variable to static, so its value will be independent of the instance to which it is linked:

private static int nInstancias = 0;

and within the builder of A:

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 as well. 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{

}

Upshot:

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

Working: https://ideone.com/gPyfaD

Reference:

  • thank you very much! I’ve been trying to figure this out for so long

Browser other questions tagged

You are not signed in. Login or sign up in order to post.