title: Cloning subclasses in Java
body: <p>I need to clone a subclass in Java, but at the point in the code where this happens, I won't know the subclass type, only the super class. What's the best design pattern for doing this?</p>
  
  <p>Example:</p>
  
  <pre><code>class Foo {
      String myFoo;
      public Foo(){}
      public Foo(Foo old) {
          this.myFoo = old.myFoo;
      }
  }
  
  class Bar extends Foo {
      String myBar;
      public Bar(){}
      public Bar(Bar old) {
          super(old); // copies myFoo
          this.myBar = old.myBar;
      }
  }
  
  class Copier {
      Foo foo;
  
      public Foo makeCopy(Foo oldFoo) {
  
          // this doesn't work if oldFoo is actually an
          // instance of Bar, because myBar is not copied
          Foo newFoo = new Foo(oldFoo);
          return newFoo;
  
          // unfortunately, I can't predict what oldFoo's the actual class
          // is, so I can't go:
          // if (oldFoo instanceof Bar) { // copy Bar here }
      }
  }
  </code></pre>