追踪类实例化对象的个数
源代码:
package 跟踪类的个数;
import java.util.Scanner;
class Test{
static int num=0;
public static int Cishu() {
return num;
}
Test(){
num++;
System.out.println("无参构造函数被执行。");
}
}
public class Genzong {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scan=new Scanner(System.in);
Test []t;
t=new Test[100];
int n;
System.out.println("请输入实例化的对象的个数:");
n=scan.nextInt();
for(int i=0;i<n;i++) {
t[i]=new Test();
}
System.out.println("一共实例化了:"+Test.Cishu()+"个对象。");
}
}
总结:
因为储存实例化对象次数的变量是属于所有对象的,因此我使用静态整型变量对次数储存,并定义了一个静态的函数返回次数这个整型数据,并在构造函数里面写一个次数变量加一的语句,每次执行构造函数次数变量都会加一,若想要得到实例化的对象的个数,只需调用返回次数变量的函数即可。