假设您有不同的员工,但每个员工类都有一个salary()方法。如何创建这些不同的对象并将其放入ArrayList中使用方法salary()?
public void betaalSalarissen(){
for(int counter = 0;werknemers.size()>counter;counter++){
Class objectClass = werknemers.get(counter).getClass();
**objectClass.salaris();** //this won't work, help please!
}
}
public void neemInDienst(Object persoon){ //objects from different classes, different employees
werknemers.add(persoon);
}
答案 0 :(得分:2)
没有理由去上课;只使用多态。
public class Employee {
public double salaris() { ... }
}
public class CommissionedEmployee extends Employee {
@Override
public double salaris() { ... }
}
List<Employee> employees = new ArrayList<>();
// add some employees of whatever subtype(s)
for (Employee e : employees) {
e.salaris();
}
答案 1 :(得分:1)
这里的快速解决方案是从werknemers.get(counter)``to your
Employee`类(类名猜猜)中转换结果
((Employee)werknemers.get(counter)).salaris();
但是从长远来看,你应该将一个泛型参数应用于集合变量和方法参数:
private Collection<Employee> werknemers = new ArrayList<>();
public void neemInDienst(Employee persoon){ //objects from different classes, different employees
werknemers.add(persoon);
}
然后你就可以简单地迭代元素而不像ChiefTwoPencils建议那样进行演绎。