我有一个employee类,我希望所有员工的年龄都增加一个,使用一种方法而不循环。有可能吗?
class Employee{
Employee(int age)
{
this.age = age;
}
String name;
int age;
static void NextYear()
{
//age++;
// will increase all ages by 1
}
void increaseAge() // I don't want this method
{
age++;
}
}
public class Main
{
public static void main(String[] args) {
Employee e1 = new Employee(23);
Employee e2 = new Employee(34);
Employee.NextYear(); // want increase all ages by one
System.out.println("e1 age " + e1.age); // need 24
System.out.println("e2 age " + e2.age); // need 35
}
}
1条答案
按热度按时间jhiyze9q1#
可以使用静态字段,但我不建议这样做。
为什么不推荐这种方法?
静态变量更难测试,需要额外的关注和多线程环境的额外同步。在这样一个简单的场景中,您将引入不必要的复杂性。