2014-12-22 1 views
1

아래의 코드가 작동하지 않는 이유를 알고 있습니다. 이는 convolusion이 Base이 아니라 Derived이 아니기 때문입니다. 이 코드는 간단하고 자기 참조가 있습니다. 나는 'self-referencing class'를 확장 시켰고, 나는 그 문제에 집착했다.Java Self Reference with Inhertiance

class Base 
{ 
    public int important_data; 
    protected Base child; 

    public int sum() 
    { 
     if(child != null) 
     { 
      return important_data + child.sum(); 
     } 
     else 
     { 
      return important_data; 
     } 
    } 
} 

class Derived extends Base 
{ 
    public int more_important; 

    public int convolusion() 
    { 
     if(child != null) 
     { 
      return more_important*important_data + child.convolusion(); 
     } 
     else 
     { 
      return more_important*important_data; 
     } 
    } 
} 

그런 다음 가능한 방법이 있습니까? 당신이 child 멤버를 초기화 할 경우 당신은 표시되지 않습니다

if(child != null && child instanceof Derived) 
{ 
    return more_important * important_data + ((Derived)child).convolusion(); 
} 
+1

convolusion을 호출 할 때 자식이 유도 유형인지 어떻게 확인할 수 있습니까? –

+1

'child'는'convolusion()'메소드에 대해 모른다. – Braj

+0

@Braj 글쎄, 실제로 자기 참조 클래스가있는 Tree를 사용하고 있습니다. 일종의 DFS를 사용하여 반복을하고 싶습니다. 그리고 원래의 Tree 클래스를 확장하고 싶습니다. 또한 null이 붙은 감시 카메라가 있습니다. 따라서 아무 어린이에게 도달하지 않으면 멈출 것입니다. – Phryxia

답변

2

또는, 당신은 일반적인 기본 클래스를 사용할 수 있습니다

class Base<T extends Base> { 
    private T child; 
    private int importantData; 

    Base(T child) { 
     this.child = child; 
    } 

    Base() { 
     this(null); 
    } 

    public int sum() { 
     if (child != null && child != this) { 
      return importantData + child.sum(); 
     } else { 
      return importantData; 
     } 
    } 

    protected T child() { 
     return child; 
    } 

    protected int importantData() { 
     return importantData; 
    } 
} 

class Derived extends Base<Derived> { 
    private int moreImportant; 

    public int convolusion() { 
     if (child() != null && child() != this) { 
      return moreImportant * importantData() + child().convolusion(); 
     } else { 
      return moreImportant * importantData(); 
     } 
    } 
} 

가이 유형의 안전한 취급을 얻을이 방법은, 어떤 캐스팅이 필요하지 않습니다를.

+0

정말 안전함에 의미가 있습니다 (특히! = this)! 그러나 제네릭 클래스를 모르기 때문에 이에 대해 더 공부해야합니다. – Phryxia

0

당신은 뭔가를 시도하고, 아이의 유형을 보장 할 수 있습니다. child.convolusion()에 전화하려면 childDerived이어야하며 Derived으로 전송해야합니다.

public int convolusion() 
{ 
    if(child != null && child instanceof Derived) 
    { 
     Derived d = (Derived) child; 
     return more_important*important_data + d.convolusion(); 
    } 
    else 
    { 
     return more_important*important_data; 
    } 
}