动手动脑 -类与对象

类的静态字段和构造函数,可以跟踪某个类所创建对象的个数,写一个类,在任何时候都可以向他查询“你已经创建了几个对象”

package subway;

public class test{
private static int n;

public test()
{
n++;
}//构造函数

public static int value()
{
return n;
}

public static void main(String[] args) {
// TODO 自动生成的方法存根
test a1=new test();
test a2=new test();
test a3=new test();
test a4=new test();
System.out.println("已创建对象个数为 :"+test.value());
}

}

 

 

 

2.

public class t

 

est

{
public static void main(String[] angs)
{ Foo objl=new Foo();
}
}
class Foo{
int value;
public Foo(int initValue) {
    value=initValue;
}
}

无法通过编译,错误原因:

构造函数Foo未定义

 

posted @ 2018-10-22 07:52  阡墨  阅读(90)  评论(0)    收藏  举报