title: Best practices for extending an object graph in Java
body: <p>Consider an immutable (due to it being an external dependency, such as from a library) object graph such as:</p>
  
  <pre><code>public class A {
      private B reference;
      private List&lt;C&gt; moreReferences = new ArrayList&lt;&gt;();
  
      public void setReference(B ref) {
          reference = ref;
      }
  
      public B getReference() {
          return reference;
      }
  
      public addMoreReference(C ref) {
          moreReferences.add(ref);
      }
  
      public List&lt;C&gt; getMoreReferences() {
          return moreReferences;
      }
  }
  
  public class B {
      private A backlink;
  
      public void setBacklink(A link) {
          backlink = link;
      }
  
      public A getBacklink() {
          return backlink;
      }
  }
  
  public class C {}
  
  </code></pre>
  
  <p>What are best practices when attempting to extend all of those classes? Let's assume I'm subclassing all three classes: <code>MyA</code>, <code>MyB</code> and <code>MyC</code>, adding additional methods and fields to all of them. Then I'm always facing the issue that <code>MyA::getReference()</code> still returns instances of <code>B</code> even though I would need <code>MyB</code> here. Typecasting everything doesn't seem like an elegant solution and leads to issues as soon as Collections or Generics are involved: <code>MyA::getMoreReferences()</code> can't be simply cast from <code>List&lt;C&gt;</code> to <code>List&lt;MyC&gt;</code>. I considered covariant return types (overriding the return type of a method in my subclass), but this also fails when Generics are involved.</p>
  
  <p>What patterns or practices are recommended in this case? I'm not so much looking for a simple "fix" to specific issues, but rather a versatile pattern to base my class hierarchy on.</p>