你已经创建了多少个对象?

使用类的静态字段和构造函数,我们可以跟踪某个类所创建对象的个数。请写一个类,在任何时候都可以向它查询“你已经创建了多少个对象?”。 

package d;
import java.util.Scanner;
public class hanshu {
public hanshu()
{
System.out.println("创建对象成功!");
}
public static void main(String[] args) {
Scanner input =new Scanner(System.in);
Boolean flag=true;
int i=1;
while(flag)
{
hanshu a=new hanshu();
System.out.println("是否创建对象?Y or N");
char c=input.next().charAt(0);
if(c=='Y'||c=='y')
{
flag=true;
i++;
}
else
{
flag=false;
System.out.println("创建了"+i+"个对象");
}
}
}
}

原文地址:https://www.cnblogs.com/lxdjieshang/p/7698957.html