설정 시도 중 Person class
실수로 변경할 수 없도록 클래스의 정보를 캡슐화하는 데 문제가 발생했습니다. 클래스는 setters/getters를 사용하여 캡슐화 할 때를 제외하고는 완벽하게 작동합니다. 제가 생각하기에는 스택이 가득 찰 때까지 메소드가 반복적으로 반복된다는 것입니다. 내가 //#####//
에 표시된 라인을 변경하는 경우Java StackOverflow 캡슐화
// 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);
나는 아이들을 비공개로하고 싶지만이 루프를 벗어나는 방법을 모르겠다.
이것은 다소 숙제와 관련이 있지만 과제가 전체 점수로 완료되고 수정되었으므로 데이터를 캡슐화하려고합니다.
'setFather()'에서 당신은'addChild()'를 호출했고'addChild()'에서는'setFather()'를 다시 호출했다. 이것이 스택 오버 플로우가 발생한 이유입니다. – shuangwhywhy