This page contains an archived post to the Java Answers Forum made prior to February 25, 2002.
If you wish to participate in discussions, please visit the new
Posted by Matt Gerrans on February 05, 2002 at 8:40 PM
> > I have a class one of whose attributes is a interface. A interface can not be clonable so how can I deepcopy the class. On the other hand, how to deep copy a list if the item of the list is a unknown object?
> > thanks very much.
> Create another interface that extends your interface and extends Serializable also. Let all your classes implement Serializable interface. This way you can use ObjectOutputStream to write this object some output stream, from which you can read back your object. This will enable you to create new copy of your object. This is pain in the ass, but what can you do. If your project is really big - good luck.
> Remember, all third party classes also must be extended to implement Serializable, otherwise ObjectOutputStream's method writeObject will throw you an NotSerializableException.
Why can't an
Cloneable? Maybe the problem you were having is using the keyword
implements when you should have been using
extends. Also, the performance of serializing is an order of magnitude (at least) slower than cloning, so unless you only have a few objects, you will prefer cloning. Of course, if they are going across the network, then serializing is what you want. Here is a simple example of making an
interface Copyable extends Cloneable
public class DeepCopy implements Copyable
String quote = "Ack! I can't think of anything to say!";
public void SaySomething()
public static void main(String  args)
DeepCopy instance = new DeepCopy();
DeepCopy another = null;
another = (DeepCopy)instance.clone();
System.out.println( "Sorry, can't clone until the moral and " +
"ethical issues have been settled.");