• Post Reply Bookmark Topic Watch Topic
  • New Topic

clone()  RSS feed

 
A Kumar
Ranch Hand
Posts: 980
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

According to the API..



By convention, the returned object should be obtained by calling super.clone.


So in my class...i have to override the clone() if i want to clone a object of this class....



When we call super.clone...are we not calling the clone method of the
Object class and in that case how are we getting the cloned object of our class..??

Tx
 
Stuart Gray
Ranch Hand
Posts: 410
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm not an expert at clone methods, but I think the idea is that you call super.clone(), and then you must do some additional work to clone the instance variables of your subclass.

You don't just return what super.clone returns because as you say, that would just copy the super class object.
 
phil shea
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Apart from simply cloning, all mutable fields need to be made independent of this object. Just to prevent unwanted access to this object's internal state. (correct me if i am wrong)

-phil
 
A Kumar
Ranch Hand
Posts: 980
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Thanks ...

So are u saying that when we try to clone an object..


we should override the clone() method with access specifier as public..
(this is sure)..

Then we would be returned the object as u said..and lastly we should
clone the instance variables.

But by clone are we not making a copy of the object when we call clone()

including the instance variables........



Regards
 
Rick O'Shay
Ranch Hand
Posts: 531
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, the idea is that you call super.clone() but do you see the problem with Object.clone()? It's protected. Is your class part of java.lang? No, so how can you call Object.clone()? The answer is a giant hack in the JVM.

Because clone() is utterly unreliable it's of no value. you should implement your own clone:

public class Rocket {
public Rocket( Rocket rocket ) { copy here }
public copy( Rocket rocket ) { return new Rocket( rocket ); }
}
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!