title: How to handle self reference and inheritance in Java
body: <p>I would like the field "children" to contain a list of objects with the containing object's type. However, when inherited, I get errors because of downcasting. What strategies can I use to keep the hierarchy, yet be able to access the child objects appropriately?</p>
  
  <pre><code>public class Node&lt;T&gt;{
  
      protected T value;
      protected Node&lt;T&gt; parent;
      private ArrayList&lt;Node&lt;T&gt;&gt; children;
  
      public Node(T value){
          this.value = value;
          this.children = new ArrayList&lt;Node&lt;T&gt;&gt;();
      }
  
      public ArrayList&lt;Node&lt;T&gt;&gt; getChildren(){
          return this.children;
      }
  
      //...other methods...//
  
  }
  </code></pre>
  
  <p>When I try to call getChildren() in this class, I get a "type mismatch" error because it's trying to downcast.</p>
  
  <pre><code>public class DecidableTree&lt;T extends Decidable&lt;T&gt;&gt; extends Node&lt;T&gt;{
  
      public DecidableTree(T value) {
          super(value);
      }
  
      public randomInvolvedFunction(){
          //...other code...//
          for(DecidableTree&lt;T&gt; child : this.getChildren()){
              child.decidableTreeSpecificMethod();
          }
          //...other code...//
      }
  
      //...other methods...//
  
  }
  </code></pre>
  
  <p>Unfortunately I can't just override the getChildren() function because the return types have to match.</p>