File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes I/O and Streams and the fly likes problem i faced in cloning Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » I/O and Streams
Bookmark "problem i faced in cloning" Watch "problem i faced in cloning" New topic
Author

problem i faced in cloning

sathish gopal
Greenhorn

Joined: Dec 30, 2000
Posts: 21
code for cloning objects
class demo implements Cloneable
{
int x=5;
int y=10;
public demo cloning() throws CloneNotSupportedException
{
return (demo)super.clone();
}
}
class clonedemo
{
public static void main(String args[]) throws CloneNotSupportedException
{
demo d1=new demo();
demo d2= d1.cloning();
System.out.println("d1.x:" +d1.x +"d1.y:" +d1.y);
System.out.println("d2.x:" +d2.x +"d2.y:" +d2.y);
d2.x=1000;
d2.y=2000;
System.out.println("d2.x:" +d2.x +"d2.y:" +d2.y);
System.out.println("d1.x:" +d1.x +"d1.y:" +d1.y);
}
}
output:
d1.x:5 d1.y:10
d2.x:5 d2.y:10
d2.x:1000 d2.y:2000
d1.x:5 d1.y:10
Eventhough the object d2 is cloned properly, Why is that the last two SOP(print) statements are not the same.Please help me in
this Regard. Thank you
Carl Trusiak
Sheriff

Joined: Jun 13, 2000
Posts: 3340
There is nothing wrong with your code or the output, it's exactly what to expect. Cloning creates a complete new object that has the same values of the original. After you cloned d1 to d2, they both have the same values. When you modify d2, since it is a seperate object, that in no way affects the values of d1.
Hope this helps


I Hope This Helps
Carl Trusiak, SCJP2, SCWCD
sathish gopal
Greenhorn

Joined: Dec 30, 2000
Posts: 21
if u r cloning an object it'll make a bitwise copy of it. so any changes in the cloning will affect the original.that is the use of cloning.but here i'm changing the values of variables associated with the clone object . But the values of the original object are not being changed. why ? or give me the correct use of cloning.
Muhammad Ali
Greenhorn

Joined: Dec 04, 2000
Posts: 28
You are right when you say that cloning makes a copy. Note the word "copy". When you change the "copy" it gets changed. But since its a separate thing / object, the original doesn't get changed. As simple as that.
Muhammad Ali Shah
FAST ICS, Karachi.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: problem i faced in cloning
 
Similar Threads
serialization problem
Can objects share each other's private data ?
Use Case where hashCode() is required & not equals()
system.out.println
Multiple Threads Accessing Multiple Methods Independently