跟踪某个类所创建对象的个数
问题:使用类的静态字段和构造函数,我们可以跟踪某个类所创建对象的个数。请写一个类,在任何时候都可以向它查询“你已经创建了多少个对象?”
public class Text { public static int num;//静态字段 public Text() { num++; System.out.printf("你已经创建了%d个对象\n",num); }//构造函数 public static void main(String[] args) { num=0; Text a=new Text(); Text b=new Text(); Text c=new Text(); } }
运行结果:
        
 
                    
                     
                    
                 
                    
                
 
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号