这更多的是谁应该能够调用方法而不是它访问多少对象等问题。
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
。