Manager和Employee类都是EnterpriseMember的子类。如何为Employee类编写“getManager”方法(返回在其报表列表中包含此Employee的Manager实例)?提前致谢!
public class Manager extends EnterpriseMember {
/*Fields */
private List reports = new ArrayList();
/*Constructor */
public Manager(String name){
super(name);
}
/*Methods */
public void addReport(Employee employee){
reports.add(employee);
}// How can "employee" know it is in this List?
}
public class Employee extends EnterpriseMember {
/*Constructor */
public Manager(String name){
super(name);
}
/*Methods */
public Manager getManager(){
return ???;
}
}
像这样的东西:
public class Manager {
private List<Employee> reports = new ArrayList<Employee>();
public void addReport(Employee e) {
if (e != null) {
this.reports.add(e);
e.setManager(this);
}
}
}
public class Employee {
private Manager manager;
public void setManager(Manager m) {
if (m != null) {
this.manager = m;
}
}
}
如果不清楚,您应该添加所需的所有其他方法。我只说明了如何更新Manager
中的Employee
引用,当它被添加到直接报告的List
时。
你还应该有一个removeReport
方法,从Employee
中删除List
并将其Manager
设置为null
。
你打算如何在这个Employee
找到一个List
?按名字?员工ID?提示:考虑适当地为你的课程重写equals
和hashCode
。
是不是Managers
也Employees
?老板有没有老板?这是一个层次结构,一棵树。
通常,具有不同属性的对象如下所示:
public class Employee extends EnterpriseMember {
private Manager manager;
private String name; // You probably don't need this because you defined it in the Superclass.
.
.
.
/*Constructor */
public Employee(String name){
super(name);
}
/*Methods */
public Manager getManager(){
return manager;
}
public void setManager(Manager manager){
this.manager = manager
}
// Other getters and setters for the attributes.
}