File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

problem i faced in cloning

 
sathish gopal
Greenhorn
Posts: 21
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3340
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
sathish gopal
Greenhorn
Posts: 21
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 28
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic