Is this a valid way to count instances of objects? Or should I not override finalize?
public class MyClass{
private int instances;
public MyClass(){
Mark instances
as static volatile
. And secondly, never override the finalize
method. Also, in the code AS-IS, note that you can't access to instances
variable in your public static int getInstances
method.
If I get what you are trying to accomplish, you want to keep count of the number of instances of MyClass that have been created in your application. If that's the case, you need to declare the instances variable and the getInstances method static.
public class MyClass{
private static int instances;
public MyClass(){
instances++;
}
@Override
public void finalize(){
instances--;
}
public static int getInstances(){
return instances;
}
}
Also, I would rename instances to instancesCount (or simply count) and do the same rename for the getInstances method.