How to Count Number of Instances of a Class

后端 未结 9 1347
小鲜肉
小鲜肉 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

    Since static variables initialized only once, and they're shared between all instances, you can:

    class MyClass {
    
        private static int counter;
    
        public MyClass() {
            //...
            counter++;
        }
    
        public static int getNumOfInstances() {
            return counter;
        }
    }
    

    Read more about static fields in the JLS - 8.3.1.1. static Fields:

    If a field is declared static, there exists exactly one incarnation of the field, no matter how many instances (possibly zero) of the class may eventually be created. A static field, sometimes called a class variable, is incarnated when the class is initialized (§12.4).

    Note that counter is implicitly set to zero

提交回复
热议问题