clone - Cloning subclasses in Java -


i need clone subclass in java, @ point in code happens, won't know subclass type, super class. what's best design pattern doing this?

example:

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) {          // doesn't work if oldfoo         // instance of bar, because mybar not copied         foo newfoo = new foo(oldfoo);         return newfoo;          // unfortunately, can't predict oldfoo's actual class         // is, can't go:         // if (oldfoo instanceof bar) { // copy bar here }     } } 

if have control of classes trying copy, virtual method way forward:

class foo {     ...     public foo copy() {         return new foo(this);     } } class bar extends foo {     ...     @override public bar copy() {         return new bar(this);     } } 

(ideally make classes either abstract or final.)


Comments

Popular posts from this blog

asp.net - repeatedly call AddImageUrl(url) to assemble pdf document -

java - Android recognize cell phone with keyboard or not? -

iphone - How would you achieve a LED Scrolling effect? -