title: Extending a class such that any parent class can be cast to it, in Java
body: <p>I have a feeling this is impossible, but if not it would be very useful.</p>
  
  <p>I’m trying to extend a parent class in a way that the child class only has new methods, no new constructors, no new fields. So the underlying data structure of the child class is identical to the parent class. This tends to occur when I want to give added functions to a built in java class (e.g. <code>Vector3d</code>). Given that the underlying data is identical is it possible in any way to downcast an object initialized as the parent class to the child class so I can use the added functionality. As an example of what I mean see below</p>
  
  <pre><code>import javax.vecmath.Vector3d;
  
  public class Vector3dPlus extends Vector3d{
      //same fields, same constructors as Vector3d
  
      public double extraMethod(){
          return x+y+z;
      }
  }
  </code></pre>
  
  <p>Try to use the new method added to Vector3d</p>
  
  <pre><code>import javax.vecmath.Vector3d;     
  
  public class Test {
  
      public static void main(String[] args) {
          Vector3d basic=new Vector3d(1,2,3);
  
          useExtraMethod(basic); //this line correctly raises an exception, but is there a way around that
      }
  
      public static void useExtraMethod(Vector3dPlus plus){
          System.out.println(plus.extraMethod());
      }
  }
  </code></pre>
  
  <p>Clearly java gets upset with this because usually we can't guarantee that <code>Vector3dPlus</code> methods will work with all <code>Vector3d</code>. But is there anyway I can say to java that the underlying data structures are the same and so allow all downcasting from all <code>Vector3d</code> to  <code>Vector3dPlus</code>.</p>
  
  <p>The current way I deal with this is to put all the extra methods in a generic utilities class, but that's obviously a bit horrible</p>