Create a program that allows you to see how many objects have been created in a class

1

This time I would like to know what would be the smartest and cleanest way to create a program that says how many objects have been created in a class .

I have tried to do it in the following way:

    /*Crear un programa que le permita ver cuantos objetos se han creado de una clase

public class CounterObjects {

static int contador;

public static void main(String[]args){

    ContadorObjetos obj1=new ContadorObjetos();
    ContadorObjetos obj2=new ContadorObjetos();

    System.out.println("Actualmente existen "+contador+"objetos en esta clase");
}

}

But actually the counter variable gives me 0 . I have heard that it could be done with an Array ... but I prefer to make sure and ask around here.

I appreciate your clear and understandable answers. Thanks in advance

    
asked by Brian Martínez 05.06.2016 в 23:42
source

2 answers

1

Create a static variable within the class that increments with each new instance:

public class miClase {
    private static int cantidad;
    public miClase() {
        cantidad++;
    }
    public static int getCantidad() {
        return cantidad;
    }
    protected void finalize() throws Throwable {
        cantidad--;
        super.finalize();
    }
}

Then you just have to apply the getCantidad method:

miClase clase1 = new miClase();
miClase clase2 = new miClase();

System.out.println ("Cantidad: " + miClase.getCantidad();
    
answered by 06.06.2016 / 00:04
source
1

The simplest option is to increase the value of the counter in the constructor of the class:

public class LaClase {
    static int contadorInstancias = 0;

    public LaClase() {
        contadorInstancias++;
        //resto de lógica del constructor
    }

    public static int getContadorInstancias() {
        return contadorInstancias;
    }
}

If you have multiple constructors, then I recommend using an initialization block that will be executed regardless of which constructor is invoked:

public class LaClase {
    static int contadorInstancias = 0;
    {
        contadorInstancias++;
    }
    public LaClase() {
        //código de constructor
    }
    public LaClase(String arg) {
        //código de constructor
    }

    public static int getContadorInstancias() {
        return contadorInstancias;
    }
}

Now, consider that this alternative suffers from a serious problem in concurrent environments. For this case, it would be better to use a AtomicInteger instead of a variable of type int :

public class LaClase {
    static AtomicInteger contadorInstancias = new AtomicInteger(0);

    public LaClase() {
        contadorInstancias.incrementAndGet();
        //código de constructor...
    }

    public static int getContadorInstancias() {
        return contadorInstancias.get();
    }
}
    
answered by 06.06.2016 в 00:05