所以我已经在这个问题上停留了一段时间了。基本上,我想让复合组件知道其父级。当我尝试访问参数中的父对象时,当我尝试对其进行记录时,它为我提供了null,但如果我尝试打印出该对象的名称,则不会抛出错误。很抱歉使用格式不正确的代码,我们将不胜感激,如果您不清楚或不清楚该问题,请告诉我是否可以添加任何内容。谢谢!
这是员工班级
public class Employee {
protected String name;
protected Employee parent;
public Employee() {
this.parent = null;
this.name = "name not set";
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Employee getParent() {
return parent;
}
public void setParent(Employee parent) {
this.parent = parent;
}
}
这是开发人员类
public class Developer extends Employee {
protected ArrayList<Employee> staffList;
public Developer() {
super();
this.staffList = new ArrayList<Employee>();
}
public void add(Employee e) throws Exception {
System.out.println(e.getParent()); //prints null even though the parameter has parent
if (e.getParent() instanceof Developer) {
throw new Exception("You cannot add staff when your lead is a dev");
} else if (e instanceof Manager) {
throw new Exception("You cannot add manager as your staff bcs u r a dev");
}
e.setParent(this);
this.staffList.add(e);
}
public void printData() {
for(Employee e : staffList) {
System.out.println(e.name);
}
}
}
这是经理班
public class Manager extends Employee {
protected ArrayList<Employee> staffList;
public Manager() {
// TODO Auto-generated constructor stub
super();
this.staffList = new ArrayList<Employee>();
}
public void add(Employee e) {
e.setParent(this);
this.staffList.add(e);
}
public void printData() {
for(Employee e : staffList) {
System.out.println(e.name);
}
}
}
在Main.java
public static void main(String[] args) {
Manager man1 = new Manager();
man1.setName("man1");
Developer dev1 = new Developer();
dev1.setName("dev1");
man1.add(dev1);
Developer dev2 = new Developer();
dev2.setName("dev2");
man1.add(dev2);
Developer dev3 = new Developer();
dev3.setName("dev3");
dev2.add(dev3);
System.out.println(dev3.getParent()); //composite.Developer@2a139a55
Developer dev4 = new Developer();
dev4.setName("dev4");
dev3.add(dev4);
}
答案 0 :(得分:0)
缺少的呼叫代码。您在Developer.add()中显示为null的打印语句表明您尚未设置父级。检查调用代码,以确保您确实设置了父代。
要考虑的其他一些事项。 Developer.add()方法中的逻辑似乎有些偏离。如果您要添加的员工的父母是开发人员,则会引发异常。这表明您试图将员工 转移 到该开发人员的逻辑。那是你的意图吗?
我猜你想说的是开发人员不能拥有员工,因为他的老板是一名开发人员,那么if声明应该是:
if (this.parent !== null && this.parent instanceof Developer) throw...
例如,如果调用代码类似于:
dev.setParent(new Developer());
dev.add(new Employee()); <-- throw exception "You can't have staff 'cause your boss is a dev, and not a manager."