1. 程式人生 > >跟蹤建立類的個數

跟蹤建立類的個數

          跟蹤建立類的個數,運用到一個靜態成員,在每次呼叫建構函式的時候就會完成加一操作,設定get方法來進行輸出靜態成員的值,來顯示建立了幾個類。

下面是原始碼:

import java.util.Scanner;

public class Sumlei {

    public static void main(String[] args) {
        Scanner reader=new Scanner(System.in);
        int i;
        Lei []le;
        le
=new Lei[100]; Lei s=new Lei(); do { System.out.println("***********************"); System.out.println("1、建立"); System.out.println("2、顯示建立個數"); System.out.println("3、退出"); System.out.println("***********************"); i=reader.nextInt();
switch(i) { case 1:{ int k=0; for(int m=0;m<100;m++) { if(le[k]!=null)k=m; else break; } le[k]=new Lei(); };break; case 2:{ System.out.println("你已經建立了"+s.getTime()+"個物件"); };break
; case 3:break; default:System.out.println("輸入錯誤!"); } }while(i!=4); } } class Lei{ private String s; static int time=0; Lei(){ time++; } Lei(String s){ this.s = s; time++; } public String getS() { return s; } public void setS(String s) { this.s = s; } public int getTime() { return time; } }