0

設定しようとするPerson classと、誤って変更されないようにクラス内の情報をカプセル化しようとして問題が発生しました。セッター/ゲッターを使用してカプセル化しようとする場合を除いて、クラスは完全に正常に機能します。問題は、スタックがいっぱいになるまでメソッドが互いにループしてしまうことだと思います。

これは作業コード(カット)です:

// 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);。スタックオーバーフローが発生します。

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

子供たちをプライベートにしたいのですが、このループから逃れる方法がわかりません。

これはやや宿題に関連していますが、割り当てはフルスコアで行われ、修正されています。データをカプセル化したいだけです。

4

1 に答える 1

2

(setFatherからの)addChildへの呼び出しは、setFatherを再度呼び出します。

変更してみてください

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

の線に沿って何かに

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

このチェックにより、無限ループから抜け出します。setChildメソッドを呼び出す前に、setFatherメソッドで父親​​を設定していることを確認してください。

于 2013-03-06T18:08:12.547 に答える