How to Count Number of Instances of a Class

后端 未结 9 1352
小鲜肉
小鲜肉 2020-12-15 10:46

Can anyone tell me how to count the number of instances of a class?

Here\'s my code

public class Bicycle {

    //instance variables
    public int          


        
9条回答
  •  一个人的身影
    2020-12-15 11:33

    In addition, you should override finalize method to decrement the counter

    public class Bicycle {
    ...
        public static int instances = 0;
    
        {
            ++instances; //separate counting from constructor
        }
    ...
        public Bicycle(int gear, int speed, int seatHeight, String color) {
            gear = 0;
            speed = 0;
            seatHeight = 0;
            color ="Unknown";
        }
    
        @Override
        protected void finalize() {
            super.finalize();
            --instances;
        }
    
    }
    

    You should have in mind that static variables are CLASS scoped (there is no one for each instance, only one per class)

    Then, you could demonstrate instance decrement with:

    ...
    System.out.println("Count:" + Bicycle.getNumOfInstances()); // 2
    bicycle1 = null;
    bicycle2 = null;
    System.gc(); // not guaranteed to collect but it will in this case
    Thread.sleep(2000); // you expect to check again after some time
    System.out.println("Count again:" + Bicycle.getNumOfInstances()); // 0
    

提交回复
热议问题