• Post Reply Bookmark Topic Watch Topic
  • New Topic

Clone Method Query in Java  RSS feed

 
Vaibhav Gargs
Ranch Hand
Posts: 116
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have certain doubts regarding the clone method in Java:

1. The clone method is present in Java class as protected. When I implements the cloneable interface in my class, still I don't get the clone() method by its own in eclipse. I need to override the clone() method in my class to make it available in Eclipse suggestions. Why it is so? Since it is already present in Object class, shouldn't it be available in suggestions?

2. In my implementation of clone() method, I just call super.clone(); again, why do I need to provide this implementation as I am just calling the super class i.e. Object class method and I have not done anything special here. So, what is the reason i need to put this code explicitly...
 
Campbell Ritchie
Marshal
Posts: 56599
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch

The clone() method is protected in order that you can override it with public access. The Cloneable interface does not define that method, because it is inherited from Object. Cloning in the Object class would be different because Object doesn't have any fields, so you would have to override the method to clone something with fields. I would suggest you read something like Effective Java by Joshua Bloch about clone(). It used to be possible to download that part of the book (chapter 3) as a PDF free of charge.
You shou‍ld not simply call super.clone() because that will simply create a shallow clone, which may have duplicates of mutable reference types as its fields; the original and the clone are not independent of each other.

Moving discussion as too difficult for this forum.
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!