Java StackOverflow encapsulation
<p>Trying to set up a <code>Person class</code> I have run into a problem trying to encapsulate the information in the class so that it cannot be changed by accident. The class works perfectly fine except for when I try to encapsulate by using setters/getters. The prblem I think is that the methods end up looping eachother until the stack is full.</p>

<p>This is the working code (a cut):</p>

<pre><code>// Set this persons father
public void setFather(Person father) {
    // Adding or changing father
    if (father != null &amp;&amp; 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);
        }
    }
}
</code></pre>

<p>Now notice if I change the line marked with <code>//#####//</code> to: <code>this.father.addChild(this);</code> I get a stackoverflow.</p>

<pre><code>private String name = null;
    private char gender;
    private Person father;
    private Person mother;
    ArrayList&lt;Person&gt; children = new ArrayList&lt;Person&gt;(0);
</code></pre>

<p>I would like children to be private but I don't know how to escape this loop.</p>

<p>This is somewhat homework related but the assignment is done and corrected with a full score, I just want to encapsulate my data.</p>
