Sample Program :
Import Java.util.Scanner;
Class A
{
public static int id=0;
Public A ()
{
id++;
System.out.println (" Create a" +id+ " object ");
}
}
public class Test
{
public static void Main (string[] args)
{
while (1>0)
{
A obj=new a ();
System.out.println (" Please select 1. continue creating Objects 2. End ");
Scanner sc=new Scanner (system.in);
int I=sc.nextint ();
if (i==2)
{
Break
}
}
}
}
Operation Result:
Create a 1 Object
Please select 1. continue creating Objects 2. End
1
Create a 2 Object
Please select 1. continue creating Objects 2. End
1
Create a 3 Object
Please select 1. continue creating Objects 2. End
1
Create a 4 Object
Please select 1. continue creating Objects 2. End
2
Using the class's static fields and constructors, we can track the number of objects created by a class. Write a class that can query it at any time "how many objects have you created?" ”。