How to Count Number of Instances of a Class

后端 未结 9 1335
小鲜肉
小鲜肉 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:42
    public class Number_Objects {
    
        static int count=0;
        Number_Objects(){
            count++;
        }
    
        public static void main(String[] args) {
    
            Number_Objects ob1=new Number_Objects();
            Number_Objects ob2=new Number_Objects();
            Number_Objects obj3=new Number_Objects();
            System.out.print("Number of objects created :"+count);
        }
    
    }
    
    0 讨论(0)
  • 2020-12-15 11:45

    If you want to count and test instances based on the number of objects created, you can use a loop to see what really is happening. Create a constructor and use a static counter

    public class CountInstances {
    public static int count;
    public CountInstances() {
        count++;
    }
    public int getInstaces() {
        return count;
    }
    public static void main(String []args) {
        for(int i= 0; i<10; i++) {  
            new CountInstances();
        }       
        System.out.println(CountInstances.count);
      } 
    }
    
    0 讨论(0)
  • 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;
        }
    
    ........
    
    0 讨论(0)
提交回复
热议问题