D15 - OOP task, Editing previous Objects when creating a new one.

OOP task

I ran into a setback that I never encountered before. There is a class that needs to have a field of it updated, according to how many objects of the class are initiated. It also must update previously made objects. That is not a problem, right? I thought i'll just have a static field that updates after each initiation by the constructor.

The thing is - Each object of this class has different values on this field, so it can't be static. The field gets a constant increase in accordance to the number of objects. I'll give an a example:

class Employee {
    int income;
    public static int numOfEmployees = 0;
    public Employee(int inc) {
        numOfEmployees++;
        income = inc + numOfEmployees * 10
    }
}

The problem with the example above: Each time an object is being made it takse a "picture" of the current value of numOfEmployees. It doesn't update already made objects, and I needed it to.

After a wide search online, I couldn't seem to find an answer, I only came across a library called "Reflection" which seemed like quite an overkill.

Eventually, the solution came up to me, as I create each object, I add it to a static list. Each time I create another object, I update the value needed for all of the objects within the list.

class Employee {
    int income;
    public static int numOfEmployees = 0;
    public static List<Employee> lst = new ArrayList<>();
    public Employee(int inc) {
        for (Employee e : lst) {
            e.income += 10;
        numOfEmployees++;
        income = inc + numOfEmployees * 10
    }
}

Note that this is increased with each object creation, but it does not ever decrease said value.

While looking quite straightforward, it may not be as obvious to programmers who encounter the situation for their first time. If anyone got a better solution (memory/speed wise), let me know!

RwK