提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
使用静态变量来计算实例
public class CountTestApp {/** from nowjava.com - 时代Java**/ public static void main(String[] args) { printCount(); for (int i = 0; i < 10; i++) { CountTest c1 = new CountTest(); printCount(); } } //来 自 nowjava.com private static void printCount() { System.out.println("There are now " + CountTest.getInstanceCount() + " instances of the CountTest class."); } } class CountTest { private static int instanceCount = 0; public CountTest() { instanceCount++; }