You will create a static member in the class that will save the instance counter.
In the constructor will increment this counter.
Just need to know how many have been instantiated or need to know how many are instantiated? If you need the second, you must decrease the counter when the object is destroyed or made available.
If it is to be decremented in the destruction, it will probably be done in the finalize()
method. If you need to do this when it is no longer used, the decrease must occur in the dispose()
method or something similar that is called whenever it is made available. Or you can use the java.lang.AutoCloseable
interface in the class and use the object to ensure that it is called, such as the try
with resources .
Example:
public class teste {
protected static int count = 0;
public teste() {
count++;
}
protected void finalize() throws Throwable {
count--;
}
public static int getInstanceCount() {
return count;
}
}
Obviously this is a simplistic implementation and will have problems in a multithreaded environment.
This operation is not atomic. You can have a thread reading the counter, let's assume that the counter is worth 1. Then another thread also reads the counter that is still worth 1. The first / em> does increment and it passes value 2. The second thread does the same and it passes value 2. But if before it was 1 then had an instance, now two new instances were created by 2 < in concurrent threads, totaling 2 instances, but the counter is worth 2. The same occurs in the decrement, counting less than it should.
To solve this would have to create some form of locking, ensuring that the operation is atomic.