How to Count Number of Instances of a Class

后端 未结 9 1351
小鲜肉
小鲜肉 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条回答
  •  旧时难觅i
    2020-12-15 11:48

    why not using a static counter?

    public class Bicycle {
    
        private static int instanceCounter = 0;
    
        //instance variables
        public int gear, speed, seatHeight;
        public String color;
    
        //constructor
        public Bicycle(int gear, int speed, int seatHeight, String color) {
            gear = 0;
            speed = 0;
            seatHeight = 0;
            color ="Unknown";      
    instanceCounter++;
        }
    
        public int countInstances(){
            return instanceCounter;
        }
    
    ........
    

提交回复
热议问题