Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Let's go over <em>cloning</em> step by step:</p> <ul> <li><p>Although, every object inherits <code>Object.clone()</code>, cloning is <strong>not</strong> ON by default. That means if you try to <code>clone()</code> some random object you would probably get a <strong><em>CloneNotSupportedException</em></strong>.</p></li> <li><p>To <em>enable</em> cloning, an object's class or one of it's super classes must implement <strong><em>Cloneable</em></strong> interface. It's just a <em>marker</em> interface without which the exception mentioned above would get thrown.</p></li> <li><p>Assuming cloning has been enabled, the default implementation is inherited as <strong><em>protected</em></strong>. So, the class can still use it to create its object's copies but it cannot be called by the public yet.</p></li> <li><p>Now, if your class wants to provide for making copies of its objects from outside of the class it can <em>override</em> <code>Object.clone()</code> as <strong><em>public</em></strong> and simply call <code>super.clone()</code> inside to still use the default implementation.</p></li> <li><p>Which brings me to the last point. The <strong>default implementation</strong> is to make a <em>shallow-copy</em> of the object which means it would simply copy all the primitives as well as reference values on to the new object. This means, complex data structures, like a <code>Map</code> would get shared since both the copies though would have two different references but they would be pointing to the same <code>Map</code>.<br /><br /> This is why an <em>override</em> most of the times has to provide its own implementation to make (what is better known as) a <em>deep-copy</em> of the object so that the clone is not sharing any state from its source object and can be modified independently without affecting other's state.</p></li> </ul>
 

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