Java 应用于实例的静态方法与实例方法

Java 应用于实例的静态方法与实例方法,java,static-methods,instance-methods,Java,Static Methods,Instance Methods,鉴于这一类 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 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
}

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

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

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

同样值得注意的是,
employeeCount
是一个基本值(int),不应该被称为对象。

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

static
字段和方法属于类而不是特定实例。因此,无论您实例化多少次
Employee
,都会有一个
intemployeecount
。每个员工对
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()
设置为非静态。但是,因为调用方法的实例根本不重要(事实上,您甚至不需要实例),因此,如果方法是非静态的,并且唯一更新值的地方是在构造函数中,如代码中所示,那么将方法设置为静态,这既方便又好,然后employeeCount值将始终为1,这可能不是您想要的。它是静态的,因为它与作为“单个对象”的
Employee
employeeCount的特定实例无关关键不在于它是作为类本身的字段还是作为类的每个实例的不同字段由类的所有实例共享。一致性是程序员想要维护的吗?@CrazyRaisans,为清晰起见编辑,强调类级别的可访问性比与私有静态变量的一致性更好。是否存在void实例方法?“将getEmployeeCount()设为静态,意味着不仅任何员工都可以调用它,员工类本身也可以调用该方法;调用该方法不需要实例”(Mshnik). 你的意思是说静态方法使一个方法成为公共的而不是私有的吗?“因为它只访问静态字段,这是有意义的。无论你调用它的是哪个实例,它都会返回相同的值”(Mshnik)。您的意思是有方法调用实例以使其返回不同的值吗?如果employeeCount增加,那么期望访问器方法getEmployeeCount的值增加难道不是必要且正确的吗?您所说的“在什么实例上调用该方法根本不重要(事实上,您甚至不需要实例),将该方法设为静态既方便又良好。”?
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