public class C {
private int i=20;
private static int cnt=0;//要写成static减少每个对象开辟空间,写成private,保证不能被外部的类直接改写,必须通过对象才能改
public C()
{
++cnt;
}
public C(int i)
{
this.i=i;
++cnt;
}
public static int getC()
{
return cnt; // return this.cnt;错误,静态方法里的属性属于类而不是对象,不能加this
}
}
public class Exercise2 {
public static void main(String[] args) {
System.out.printf("当前对象的个数为%d", C.getC());
C cc1=new C();
System.out.printf("当前对象的个数为%d", C.getC());
C cc2=new C(4);
System.out.printf("当前对象的个数为%d", C.getC());
}
}
转载于:https://blog.51cto.com/13930723/2353737