How does the clone() method work?

I've decided to spend a little time each day before programming practice to learn the api... what better place to start than the object class from which all things derive.

now I know clone() should not be used, and object serilization should be used instead (whatever that is) but this is theoretical and the definition confuses me

the default implementation returns a shadow copy.
instance variables values in one object are copied to another of the same type.
for reference types only the references are copied.

instance values of an object? isnt that object then a reference type... if I'm not mistaken isnt a ref type a class or array, how can its value be copied if it then goes on to say only a reference to it is copied.

Re: How does the clone() method work?

The original intention of the clone() method was that you could copy or clone any object of any type you want. Sometimes you don't want to clone your objects (of a certain class) so you also had to implement an empty interface to indicate that you do want your objects cloned. You still have to override the clone() method. imho all that hassle isn't worth the trouble; i.e. a copy constructor can do the job too; you do have to know the class of the object to be copied though ...

Re: How does the clone() method work?

Yeah, all objects get the clone() method since Object has it, but java has no idea what fields and data should be cloned unless you define it yourself by overriding the clone method the way Jos described.

There is no magic method in java that gives you a perfect copy of an instance (from a class you wrote yourself) without you doing a little work to tell it how to copy it. This usually isn't a problem though, because object cloning really isn't done very much (at least not in the work I've ever done) and implementing a clone() method or a copy constructor isn't more than a few lines of simple assignment code.

Re: How does the clone() method work?

Cloning can involve some quite nasty details; suppose there are two objects A and B (both of the same type) where A points to/refers to B; i.e. A ---> B (they are graph vertex objects); now if we clone A (call it A') we end up wit a situation like: A ---> B <--- A' because cloning is a shallow operation. Suppose we don't want this, so we clone every member of object A as well; we end up with this: A ---> B, A' ---> B'. But now suppose B also refers to A (i.e. its a circular graph). Better duck and hide then ...