java课后作业:记录创建对象数
题目描述:
源码:
1 public class objectCount { 2 static int cnt = 0; 3 public objectCount() 4 { 5 cnt++; 6 } 7 public static void display() 8 { 9 System.out.println("您已经创建了"+cnt+"个对象"); 10 } 11 public static void main(String[] args) { 12 // TODO Auto-generated method stub 13 objectCount obj1 = new objectCount(); 14 objectCount obj2 = new objectCount(); 15 objectCount obj3 = new objectCount(); 16 objectCount obj4 = new objectCount(); 17 display(); 18 objectCount obj5 = new objectCount(); 19 objectCount obj6 = new objectCount(); 20 objectCount obj7 = new objectCount(); 21 display(); 22 objectCount obj8 = new objectCount(); 23 objectCount obj9 = new objectCount(); 24 display(); 25 } 26 27 }
思路:
用静态变量计数,在构造函数中使变量累加即可。
运行结果: