示例程序(一)
//使用静态字段
1 public class Checkclassnumber { 2 static int num = 0; 3 { 4 num++; 5 } 6 public static void main(String[] args) 7 { 8 Checkclassnumber x1 = new Checkclassnumber(); 9 System.out.println("已创建" + num + "个对象"); 10 11 Checkclassnumber x2 = new Checkclassnumber(); 12 System.out.println("已创建" + num + "个对象"); 13 14 Checkclassnumber x3 = new Checkclassnumber(); 15 System.out.println("已创建" + num + "个对象"); 16 } 17 18 }
结果截图
示例程序(二)
//使用构造方法
1 public class Checkclassnumber3 { 2 static int num = 0; 3 Checkclassnumber3() 4 { 5 num++; 6 } 7 public static void main(String[] args) 8 { 9 Checkclassnumber3 x1 = new Checkclassnumber3(); 10 System.out.println("已创建" + num + "个对象"); 11 12 Checkclassnumber3 x2 = new Checkclassnumber3(); 13 System.out.println("已创建" + num + "个对象"); 14 15 } 16 17 }
结果截图