给定这个类
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;}
我刚刚添加静态而不是实例的方法怎么样? 我认为它可以是一个实例方法,因为它对“WorkerCount”的单个对象进行操作,该对象最初等于0。
最佳答案
这更多的是一个谁应该能够调用方法的问题,而不是它访问多少个对象等问题。
静态
字段和方法属于类,而不是特定的实例。因此,无论实例化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()
设置为非静态。但是,由于您在哪个实例上调用该方法并不重要(事实上您甚至不需要实例),因此将方法设为静态既方便又良好的做法>.
关于java - 静态方法与应用于示例的实例方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27737540/