2013-03-06 4 views
0

설정 시도 중 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); 

나는 아이들을 비공개로하고 싶지만이 루프를 벗어나는 방법을 모르겠다.

이것은 다소 숙제와 관련이 있지만 과제가 전체 점수로 완료되고 수정되었으므로 데이터를 캡슐화하려고합니다.

+0

'setFather()'에서 당신은'addChild()'를 호출했고'addChild()'에서는'setFather()'를 다시 호출했다. 이것이 스택 오버 플로우가 발생한 이유입니다. – shuangwhywhy

답변

2

addChild (setFather)를 호출하면 setFather가 다시 호출됩니다.

시도이 검사는 당신의 무한 루프 밖으로 끊어집니다

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

의 라인을 따라 뭔가

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

을 변경. 그냥 setFild 메서드에서 전에 아버지를 설정 한 있는지 확인하십시오 setChild 메서드를 호출하십시오.

+0

흠,이 클래스를 깨는 지 궁금합니다. 아무도 아이가 없어도 아버지가 없을 수 있습니다.하지만 사람은 널 아버지가있을 수 있습니다. 즉, 내가 사람 객체에 자식을 추가하면 그 자식은이 사람을 부모로서 소유해야합니다. – arynaq