代码如下,其中finalize方法为考虑到对象万一被垃圾回收时减少一次计数:
public class Example { private static int classCounter = 0; public Example() { classCounter = classCounter + 1; } public void finalize() { classCounter = classCounter - 1; } public static int getClassCount() { return classCounter; } public static void main(String[] args) { Example exp = new Example(); System.out.println(Example.getClassCount()); Example exp1 = new Example(); Example exp2 = new Example(); System.out.println(Example.getClassCount()); } }