3 回答
TA贡献1833条经验 获得超4个赞
您需要使numb
静态,以便该类的每个实例只有一个副本。事实上,每个Employee
对象都有自己的numb
.
另外,与其创建一个增加计数器的方法,不如将它放在构造函数中:
public Employee() { numb++; }
TA贡献1853条经验 获得超18个赞
numb
是一个实例变量,这意味着每个Employee
对象都有自己的numb
,由 初始化0
。
如果您希望所有Employee
实例共享相同的实例numb
,您应该创建它static
。
TA贡献1757条经验 获得超8个赞
// Java program Find Out the Number of Objects Created
// of a Class
class Test {
static int noOfObjects = 0;
// Instead of performing increment in the constructor instance block is preferred
//make this program generic. Because if you add the increment in the constructor
//it won't work for parameterized constructors
{
noOfObjects += 1;
}
// various types of constructors
public Test()
{
}
public Test(int n)
{
}
public Test(String s)
{
}
public static void main(String args[])
{
Test t1 = new Test();
Test t2 = new Test(5);
Test t3 = new Test("Rahul");
System.out.println(Test.noOfObjects);
}
}
添加回答
举报