我是Java新手,在Employee管理系统中工作。我创建了几个类,包括Employee(name,dob等),Department(dept名称,描述等)。我要求部门必须有2名雇员且不到10名。 谁能告诉我如何建立这种关联? 系类:
public class Department {
private String departmentName;
private String locationofDep;
Employee emp = new Employee()
Getter.. setter
}
public class Employee {
private String empName;
private String dob;
Getter.. setter
}
答案 0 :(得分:0)
根据问题,您应该有一个collection
Employee
个对象。因此,您必须创建Employee
Collection
,例如List
,Set
等。但是,您无法限制Collection
这两个值之间的容量。以编程方式,只有throw
和Exception
调用Collection
的getter方法时才能执行的操作。您可以将两个默认值添加到Collection
。我不相信那会对你有用。在您的代码中进行以下修改。
public class Department {
private String departmentName;
private String locationofDep;
//collection of empleyees
Set<Employee> employees = new HashSet<>();
//use this method to add employees
public void addEmployee(Employee employee) {
this.employees.add(employee);;
}
public Set<Employee> getEmployees() throws Exception {
if (this.employees.size() < 2 || this.employees.size() > 10) {
throw new Exception("Employees out of capacity");
}
return this.employees;
}
//other getters and setters should be here
}
public class Employee {
private String empName;
private String dob;
//put getters and setters
}
因此,当您使用try-catch
块