追蹤類例項化物件的個數
阿新 • • 發佈:2018-11-08
追蹤類例項化物件的個數
原始碼:
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
// 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
}
}
總結:
因為儲存例項化物件次數的變數是屬於所有物件的,因此我使用靜態整型變數對次數儲存,並定義了一個靜態的函式返回次數這個整型資料,並在建構函式裡面寫一個次數變數加一的語句,每次執行建構函式次數變數都會加一,若想要得到例項化的物件的個數,只需呼叫返回次數變數的函式即可。