Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/317.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
是否可以不使用循环更新Java中的所有对象?_Java_Class_Oop - Fatal编程技术网

是否可以不使用循环更新Java中的所有对象?

是否可以不使用循环更新Java中的所有对象?,java,class,oop,Java,Class,Oop,我有一个employee类,我希望所有员工的年龄都能通过一种方法增加一岁,而不会出现循环。可能吗 class Employee{ Employee(int age) { this.age = age; } String name; int age; static void NextYear() { //age++; // will increase all ages by 1 }

我有一个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
    }
}

可以使用静态字段,但我不建议这样做

为什么不推荐这种方法

静态变量更难测试,并且需要额外的注意和与多线程环境的额外同步。在这样一个简单的场景中,您将引入不必要的复杂性

private static class Employee {

    private static int offset;

    private final String name;
    private final int age;

    private Employee(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age + offset;
    }

    public static void nextYear() {
        offset++;
    }
}

Employee e1 = new Employee("e1", 23);
Employee e2 = new Employee("e2", 34);

Employee.nextYear();

System.out.println("e1 age " + e1.getAge()); // 24
System.out.println("e2 age " + e2.getAge()); // 35

不,不可能。有些代码,在某些地方,需要循环来实现这一点。有没有一种方法看起来不像是循环?最好存储出生年份/日期(永远不会更改),并在getAge()中动态计算年龄为什么禁止循环?这是一个尚未教授循环的班级的家庭作业问题吗?非常好,谢谢