猿问

如何在不破坏封装的情况下使它们对彼此“可见”?

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

    }


}


慕田峪7331174
浏览 105回答 2
2回答

叮当猫咪

像这样的东西:public class Manager {&nbsp; &nbsp; private List<Employee> reports = new ArrayList<Employee>();&nbsp; &nbsp; public void addReport(Employee e) {&nbsp; &nbsp; &nbsp; &nbsp; if (e != null) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this.reports.add(e);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; e.setManager(this);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}public class Employee {&nbsp; &nbsp; private Manager manager;&nbsp; &nbsp; public void setManager(Manager m) {&nbsp; &nbsp; &nbsp; &nbsp; if (m != null) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this.manager = m;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}以防万一不清楚,您应该添加您需要的所有其他方法。我只说明了如何在将参考添加到直接报告时更新Manager参考。EmployeeList您还应该有一个从removeReport中删除 an并将其设置为的方法。EmployeeListManagernull你打算如何Employee在这个中找到一个List?按名字?员工ID?提示:考虑覆盖equals并hashCode适当地为您的课程。不Managers也是Employees吗?老板没有老板吗?这是一个层次结构,一棵树。

慕少森

通常具有不同属性的对象如下所示:public class Employee extends EnterpriseMember {&nbsp; &nbsp; private Manager manager;&nbsp; &nbsp; private String name; // You probably don't need this because you defined it in the Superclass.&nbsp; &nbsp; .&nbsp; &nbsp; .&nbsp; &nbsp; .&nbsp; &nbsp; /*Constructor */&nbsp; &nbsp; public Employee(String name){&nbsp; &nbsp; &nbsp; &nbsp; super(name);&nbsp; &nbsp; }&nbsp; &nbsp; /*Methods */&nbsp; &nbsp; public Manager getManager(){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; return manager;&nbsp; &nbsp; }&nbsp; &nbsp; public void setManager(Manager manager){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; this.manager = manager&nbsp; &nbsp; }&nbsp; &nbsp; // Other getters and setters for the attributes.}
随时随地看视频慕课网APP

相关分类

Java
我要回答