Java: use static fields and constructors to query the number of created objects. java Constructor
Problem: using static fields and constructors of a class, we can track the number of objects created by a class.
Please write a class and you can query it at any time, "How many objects have you created ?".
Program Design ideas:
Use static variables to specify a counter number,
When creating an object, you always need to execute the constructor once,
Then, when the constructor executes the seasonal number auto-increment,
The number of objects created at the end is displayed.
Program flowchart:
Source code:
1/** 2*3 */4 5/** 6 * @ author letter 1605-3 20163471 Wu Xin 7*8 */9 public class NumofObj {10 11/** 12*13 */14 15 private static int number = 0; 16 public NumofObj () {17 // TODO automatically generated constructor stubs 18 number ++; 19} 20 21/** 22 * @ param args23 */24 25 public static int getNumber () 26 {27 return number; 28} 29 public static void main (String [] args) {30 // TODO automatically generated method stub 31 NumofObj t1 = new NumofObj (); 32 NumofObj t2 = new NumofObj (); 33 NumofObj t3 = new NumofObj (); 34 NumofObj t4 = new NumofObj (); 35 NumofObj t5 = new NumofObj (); 36 NumofObj t6 = new NumofObj (); 37 NumofObj t7 = new NumofObj (); 38 System. out. println ("created in total" + NumofObj. getNumber () + "objects"); 39} 40 41}
The running result is as follows: