Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <blockquote> <p>As every class in Java extends from Object, so it should have clone method but still we are forced to override clone</p> </blockquote> <p>No you are not forced to override the <code>clone</code> method. In inheritance, when you inherit a class, you are not forced to override it's method. Its modifier being public or protected doesn't make much of a difference. However, if you want to invoke a method directly on <code>super</code> class reference, then that method has to be <code>public</code>. Protected methods are accessible only through inheritance. That is you can only access them through <code>subclass</code> reference. Or if you override the method, you can access them through <code>super</code> keyword.</p> <p>Having said that, you should not override <code>clone</code> method, as it is <code>broken</code>. Because, for a class to be cloned, you need to implement the <code>Cloneable</code> interface. And then your class uses the <code>clone</code> method of <code>Object</code> class instead. Because, <code>Cloneable</code> interface doesn't exactly have any method for <code>cloning</code>. It would be a better option to use <code>Copy Constructor</code> instead. </p> <pre><code>public class A { private int data; public A() { } public A(A a) { this.data = a.data; } } </code></pre> <p>For more details, I would suggest to go through this chapter of <code>Joshua Bloch's</code> Effective Java, which covers all aspects of using <code>clone</code> method.</p> <p><a href="http://my.safaribooksonline.com/book/programming/java/9780137150021/methods-common-to-all-objects/ch03lev1sec2#X2ludGVybmFsX0ZsYXNoUmVhZGVyP3htbGlkPTk3ODAxMzcxNTAwMjElMkZjaDAzbGV2MXNlYzQ=" rel="noreferrer"><strong>Effective Java- Item # 11 - Override clone judiciously</strong></a></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