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?" ”。
idea: Because the static initialization block runs only once, is a good way to record the number of times, define a static private int variable, call the constructor variable plus one, and then write a method to return the value of the variable, the implementation of the query to create the function of how many objects.
Flow chart
ImportJava.util.Scanner; Public classtestjing { Public Static voidMain (String[]args) {Jingtai a=NewJingtai (); while(true) {System.out.println ("Please select function: 1 Create object, 2 query Create object number, 0 exit!" "); Scanner SC=NewScanner (system.in); intI=Sc.nextint (); if(i==1) {a=NewJingtai (); System.out.println ("Created successfully! "); } Else if(i==2) {A.chaxun (); } Else{System.out.println (Goodbye "); return; } } }}classjingtai{Private Static intNumber ; Static{ number=0; } PublicJingtai () { number++; } Public intGetNumber () {returnNumber ; } Public voidChaxun () {intb= This. GetNumber (); System.out.println ("Created" +b+ "objects"); }}
A static variable number is defined in a class, initialized only once, creating an object number++, and several objects are created by number.
Java Applet (Classroom Assignment 03)