File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes Cloning and assigning?? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Cloning and assigning??" Watch "Cloning and assigning??" New topic

Cloning and assigning??

Vijay Kashyap
Ranch Hand

Joined: Jul 30, 2001
Posts: 74
Could any body tell me whats the difference between assigning an object to another and cloning it?

Why would I require to clone any object , cannot I assign it??
Ilja Preuss

Joined: Jul 11, 2001
Posts: 14112
You always assign references to objects. In your example, obj and obj1 are referencing the same object, that is, if you call a method on obj1 it is the same as calling a method on obj. Therefore, if you want to work on a copy of an object, you have to clone it like you did for obj2.

The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
Vijay Kashyap
Ranch Hand

Joined: Jul 30, 2001
Posts: 74
Thanks Ilja,
By this you mean that the cloned object obj2 will not share the same reference as obj but will create a new reference.
Am I right?
Dirk Schreckmann

Joined: Dec 10, 2001
Posts: 7023
Not exactly. By this he means that the cloned object obj2 will not reference the same object as obj - a new object has been created.

[How To Ask Good Questions] [JavaRanch FAQ Wiki] [JavaRanch Radio]
I agree. Here's the link:
subject: Cloning and assigning??
It's not a secret anymore!