Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The general suggestion: use a <em>copy constructor</em>. In fact, only a class itself knows how to create a clone of itself. No class can clone an instance of another class. The idea goes like this:</p> <pre><code>public class Foo { public List&lt;Bar&gt; bars = new ArrayList&lt;Bar&gt;(); private String secret; // Copy constructor public Foo(Foo that) { // new List this.bars = new ArrayList&lt;Bar&gt;(); // add a clone of each bar (as an example, if you need "deep cloning") for (Bar bar:that.bars) { this.bars.add(new Bar(bar)); } // clone the secret value this.secret = new String(that.secret); } // ... } </code></pre> <p>So if we want to clone a <code>foo</code>, we simply create a new one based on <code>foo</code>:</p> <pre><code>Foo clonedFoo = new Foo(foo); </code></pre> <p>That's the recommended way to clone an instance.</p> <hr> <p>copy constructor works well with inheritance. Consider a subclass</p> <pre><code> public ChildFoo extends Foo { private int key; public ChildFoo(ChildFoo that) { super(that); this.key = that.key; } } </code></pre> <p><code>Foo</code> has a copy constructor and <code>ChildFoo</code> simply calls it from it's own copy constructor.</p> <p>Your example is possible but not advisable. What will happen:</p> <pre><code> Foo a = new Foo(); ChildFoo b = new ChildFoo(a); </code></pre> <p>This would <em>require</em> a constructor on ChildFoo like:</p> <pre><code> public ChildFoo(Foo that) { // call the copy constructor of Foo -&gt; no problem super(that); // but how to initialize this.key? A Foo instance has no key value! // Maybe use a default value? this.key = 0; } </code></pre> <p>Technically not a challenge but <code>b</code> is not a clone of <code>a</code> because the objects don't have the same type. So this (your example) is not <em>cloning</em>.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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