0

尝试设置一个Person class我在尝试将信息封装在类中以使其不会被意外更改时遇到了问题。除了当我尝试使用 setter/getter 进行封装时,该类工作得非常好。我认为的问题是这些方法最终会相互循环,直到堆栈已满。

这是工作代码(剪辑):

// Set this persons father
public void setFather(Person father) {
    // Adding or changing father
    if (father != null && father.isMale()) {
        // If old father, remove as child
        if (this.father != null)
            this.father.removeChild(this);
        this.father = father;
        this.father.children.add(this);  //######//
    }

    // Removing father
    if (father == null) {
        // Removing old father
        if (this.father != null)
            this.father.removeChild(this);
        this.father = null;
    }
}

// Add a child to this person
public void addChild(Person child) {
    // Add child to this persons children if not already a child
    if (!this.children.contains(child)) {
        // Add this person as mother to child if female
        if (this.isFemale()) {
            child.setMother(this);
        }

        // Add this person as father to child if male
        if (this.isMale()) {
            child.setFather(this);
        }
    }
}

现在请注意,如果我将标有的行更改//#####//为:this.father.addChild(this);我得到一个 stackoverflow。

private String name = null;
    private char gender;
    private Person father;
    private Person mother;
    ArrayList<Person> children = new ArrayList<Person>(0);

我希望孩子们保持私密,但我不知道如何摆脱这个循环。

这有点与家庭作业有关,但作业已完成并以满分更正,我只想封装我的数据。

4

1 回答 1

2

您对 addChild 的调用(来自 setFather)再次调用 setFather。

尝试改变

    if (this.isMale()) {
        child.setFather(this);
    }

类似于

    if (this.isMale() && child.father != this) {
        child.setFather(this)     
    }

此检查将使您摆脱无限循环。只需确保在调用 setChild 方法之前在 setFather 方法中设置了父亲。

于 2013-03-06T18:08:12.547 回答