0

While explaining the item 11: Override clone() judiciously it says - The "only" way a superclass can provide this functionality is to return an object obtained by calling super.clone. If a clone method returns an object created by a constructor, it will have the wrong class.

  1. Why will it have a wrong class? Can't every object's clone method call its own constructor?

  2. In java you have to call the constructor to allocate the memory, right? If we aren't calling the constructor anytime during the whole chain of super.clone(), then who's allocating the memory for the clone?

Chris Martin
  • 30,334
  • 10
  • 78
  • 137
Saurabh Patil
  • 4,170
  • 4
  • 32
  • 33
  • @G.S Please read again, it's a different question. I have gone through that question and a couple of other questions as well. Both these questions are pointing to two different lines in the text and my questions are different, way different!! Don't only go by the title of that question, read the whole thing! We're asking different things. Sad to see what SO has become these days. – Saurabh Patil Mar 06 '16 at 09:04
  • 1
    read the last part of the answer, and the comment below the answer. It answers your question. – JB Nizet Mar 06 '16 at 09:08
  • @JBNizet: There is one single line in the last comment which does say something about my question 1 and it confused me more. Also, where is my question 2 discussed in that answer or comments? – Saurabh Patil Mar 06 '16 at 09:13
  • 1
    If you have a class A that implements clone() using new A(), and then define a class B that extends A, and you call b.clone(), you'll get an instance of A, instead of an instance of B. So that isn't right. As said in the answer, `clone()` does NOT call a constructor. It's a `native` method (i.e. not written in Java, but implemented by native code in the JVM), that clones the object without calling a constructor. – JB Nizet Mar 06 '16 at 09:17
  • @JBNizet Why not let A's clone() method call A's constructor. And then B's clone() method call B's constructor? And then B's constructor call super()? – Saurabh Patil Mar 06 '16 at 09:22
  • 1
    Well, you can do that, but it's an invitation for bugs: every subclass must remember that it must override clone(). And even then, if you do that, you're not sure to clone A's state correctly, because it might not be accessible by B, and you can't call super.clone(). – JB Nizet Mar 06 '16 at 09:30

0 Answers0