設定しようとする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);
子供たちをプライベートにしたいのですが、このループから逃れる方法がわかりません。
これはやや宿題に関連していますが、割り当てはフルスコアで行われ、修正されています。データをカプセル化したいだけです。