Is this a valid way to count instances of objects?

后端 未结 2 1523
说谎
说谎 2020-12-22 00:59

Is this a valid way to count instances of objects? Or should I not override finalize?

public class MyClass{
    private int instances;
   public MyClass(){
          


        
相关标签:
2条回答
  • 2020-12-22 01:09

    Mark instancesas 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.

    0 讨论(0)
  • 2020-12-22 01:27

    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.

    0 讨论(0)
提交回复
热议问题