How to Count Number of Instances of a Class

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

    One basic approach is to declare a static numeric member field thats incremented each time the constructor is invoked.

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

提交回复
热议问题