0

鉴于这个类

  public class Worker
private String name;
private static int WorkerCount = 0; // number of workers

public Worker(<*parameter list* >)
{
<*initialization of private instances variables* >
Worker++; //increment count of all worker
}

}

如果我要添加方法...

public static int getWorkerCount()
{
return WorkerCount;}

我刚刚添加静态而不是实例的方法如何?我认为它可以是一个实例方法,因为它对最初等于 0 的“WorkerCount”的单个对象进行操作。

4

2 回答 2

2

这更多的是应该能够调用方法而不是它访问多少对象等问题。

static字段和方法属于Class而不是特定的实例。因此,无论您实例化多少次Employee,都会有一个int employeeCount。每个员工对该employeeCount字段的引用都返回到同一位置。通过使用employeeCount 字段,您已经了解了这一点,只需将相同的逻辑应用于方法即可。

通过getEmployeeCount()设置静态,您是说不仅任何员工都可以调用它,而且Employee类本身也可以调用该方法;您不需要实例即可调用该方法。

Employee.getEmployeeCount(); //Valid, because getEmployeeCount() is static
Employee.name; //Invalid (non-static reference from static context) because *which* employee's name?

因为它只访问静态字段,所以这是有道理的。无论您在哪个实例上调用它,它都会返回相同的值。考虑代码:

Employee a = new Employee();
Employee b = new Employee();

System.out.println(a.getEmployeeCount()); //2
System.out.println(b.getEmployeeCount()); //2
System.out.println(Employee.getEmployeeCount()); //2

Employee c = new Employee();

System.out.println(a.getEmployeeCount()); //3
System.out.println(b.getEmployeeCount()); //3
System.out.println(c.getEmployeeCount()); //3
System.out.println(Employee.getEmployeeCount()); //3

没有什么能阻止你制作getEmployeeCount()非静态的。但是,因为在什么实例上调用该方法并不重要(事实上,您甚至不需要实例),因此创建该方法既方便又好习惯static

于 2015-01-02T05:03:12.597 回答
0

该方法应该是静态的,以允许在类级别访问员工计数。

由于employeeCount变量是静态的,因此已经为此功能设置了方法主体。Employee您可能希望以这种方式使用它,因为它会计算使用该构造函数初始化的对象的总数。

同样值得注意的是,它employeeCount是一个原始值(int),不应被称为对象。

于 2015-01-02T05:01:16.537 回答