Title: Using static fields and constructors of classes, 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?" ”。
Programming Ideas:
A static variable is explicitly referenced first, so there can be only one public class in the topic, so in the program, the reference static variable sets the number of times the object is created, so that when the number of objects created is +1, the +1 of the static variable is convenient to count, and in the public class, the number of times that the output creates the object.
Source:
Package demo; class Jishu { privatestaticint A; Public Jishu () { a++ ; } Public Static int Get () { return A; }}
Package demo; Public classNum { Public Static voidMain (string[] args) {//TODO Auto-generated method stubsJishu j1=NewJishu (); Jishu J2=NewJishu (); Jishu J3=NewJishu (); Jishu J4=NewJishu (); System. out. println ("the number of objects you have created is:"+jishu.Get()); }}
Program run:
Java fifth week after class homework