简体   繁体   中英

Calling a method on every created object

I've been wondering is there any way to call a method for EVERY object of one specific class?

Let's say I have a class:

public class Employee {
private double salary;
private boolean hired;

public double getSalary() {return salary;}
public double setSalary(double x) {salary=x;}

public boolean getHired() {return hired;}
public boolean setHired(boolean check) {hired=check;}

}

then I declare another class that extends Employee, eg Boss (because Boss is an employee too, right)

so he inherits "gets" and "sets" from Employee and also has the possibility to fire employee:

public class Boss extends Employee {

public void fireTheGuy(Employee unluckyYou) {
    boolean temp;
    temp=false;
    unluckyYou.setHired(temp);
    unluckyYou.setSalary(0.0);
}

this allows in main:

public static void main(String args[])
{
     Employee worker1 = new Employee();
     Employee worker2 = new Employee();
     Boss slacker = new Boss();
     slacker.fireTheGuy(worker1);
     slacker.fireTheGuy(worker2);
}

but what if I have like 100 employees and the Boss wants to fire them all? how this method should be called (is this even possible by some kind of loop?)

You could make all employees register themselves in a common static List . Then when the boss is told to fire everyone he just walks the list.

static List<Employee> allEmployees = new ArrayList<>();

public class Employee {
    private double salary;
    private boolean hired;

    public Employee() {
        // All employees must register themselves in the allEmployees list.
        allEmployees.add(this);
    }

    public double getSalary() {return salary;}
    public double setSalary(double x) {salary=x;}

    public boolean getHired() {return hired;}
    public boolean setHired(boolean check) {hired=check;}

}

public class Boss extends Employee {

    public void fireTheGuy(Employee unluckyYou) {
        unluckyYou.setHired(false);
        unluckyYou.setSalary(0.0);
    }

    public void fireThese(Iterable<Employee> fireThem) {
        for ( Employee e : fireThem ) {
            fireTheGuy(e);
        }
    }

    public void fireEveryone() {
        fireThese(allEmployees);
    }
}

This is an example of code of what you could do

List<Employee> employees=new ArrayList<Employee>();

employees.add(worker1);
employees.add(worker2);

for(Employee worker:employees){
    slacker.fireTheGuy(worker);
}

But like mentionned in the comments you should try to understand all the concepts behind this example.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM