在每个创建的对象上调用方法

时间:2017-10-16 16:07:50

标签: java class object methods instance

我一直想知道有没有办法为一个特定类的每个对象调用一个方法?

假设我有一个班级:

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;}

}

然后我声明另一个扩展Employee的类,例如老板(因为Boss也是一名员工,对吧)

所以他从Employee继承了“gets”和“sets”,并且还有可能解雇员工:

public class Boss extends Employee {

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

这允许在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);
}

但是,如果我有100名员工并且老板想解雇他们怎么办?应如何调用此方法(这是否可能通过某种循环?)

2 个答案:

答案 0 :(得分:1)

您可以让所有员工在共同static 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);
    }
}

答案 1 :(得分:0)

这是您可以做的代码的示例

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

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

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

但是如评论中提到的那样,你应该尝试理解这个例子背后的所有概念。