Note that there are some explanatory texts on larger screens.

plurals
  1. POclone() vs copy constructor vs factory method?
    primarykey
    data
    text
    <p>I did a quick google on implementing clone() in Java and found: <a href="http://www.javapractices.com/topic/TopicAction.do?Id=71" rel="noreferrer">http://www.javapractices.com/topic/TopicAction.do?Id=71</a></p> <p>It has the following comment:</p> <blockquote> <p>copy constructors and static factory methods provide an alternative to clone, and are much easier to implement.</p> </blockquote> <p>All I want to do is make a deep copy. Implementing clone() seems to make a lot of sense, but this highly google ranked article makes me a bit afraid.</p> <p>Here are the issues that I've noticed:</p> <h2>Copy constructors don't work with Generics.</h2> <p>Here's some pseudo-code that won't compile.</p> <pre><code>public class MyClass&lt;T&gt;{ .. public void copyData(T data){ T copy=new T(data);//This isn't going to work. } .. } </code></pre> <p>Sample 1: Using a copy constructor in a generic class.</p> <h2>Factory methods don't have standard names.</h2> <p>It's quite nice to have an interface for reusable code.</p> <pre><code>public class MyClass&lt;T&gt;{ .. public void copyData(T data){ T copy=data.clone();//Throws an exception if the input was not cloneable } .. } </code></pre> <p>Sample 2: Using clone() in a generic class.</p> <p>I noticed that clone is not a static method, but wouldn't it still be necessary to make deep copies of all the protected fields? When implementing clone(), the extra effort to throw exceptions in non-cloneable subclasses seems trivial to me.</p> <p>Am I missing something? Any insights would be appreciated.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload