aspose file tools*
The moose likes Beginning Java and the fly likes how to create a copy of java object Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "how to create a copy of java object" Watch "how to create a copy of java object" New topic
Author

how to create a copy of java object

Jignesh Patel
Greenhorn

Joined: Jul 13, 2001
Posts: 6
Hi
how can i create a copy of an object? (cloning???)
my requirement is to create a copy of an object. after that when i change some attributes of the original object; the copy of that object shall remain unchanged (ie it shall contain the older values of the attribute)
can anybody guide me in that with proper syntax??
tia
jignesh
------------------
Kaspar Dahlqvist
Ranch Hand

Joined: Jun 18, 2001
Posts: 128
Hi there, patel_o (?) !
This is one way:
import java.io.*;
public class Q implements Cloneable {
private int i;

public Q(int i) {
this.i = i;
}
public static void main(String[] a) throws Exception {
Q q = new Q(4);
Q q2 = (Q) q.clone();
q2.i = 6;
System.out.println(q.i + ", " + q2.i);
}
}
Maybe there's another...
Hope this helps!
/Kaspar
Frank Carver
Sheriff

Joined: Jan 07, 1999
Posts: 6920
"patel_o",
The Java Ranch has thousands of visitors every week, many with surprisingly similar names. To avoid confusion we have a naming convention, described at http://www.javaranch.com/name.jsp . We require names to have at least two words, separated by a space, and strongly recommend that you use your full real name. Please log in with a new name which meets the requirements.
Thanks.


Read about me at frankcarver.me ~ Raspberry Alpha Omega ~ Frank's Punchbarrel Blog
Detlev Beutner
Ranch Hand

Joined: Jul 13, 2001
Posts: 76
The solution implementing Cloneable is one way, the other is a constructor with the object itself, for example:

It is a matter of taste (and maybe time), which one you prefer. The "Cloneable"-solution is somewhat more intuitive to write, whereas the "Constructor"-solution is somewhat more intuitive to read. But as said: "A matter of taste."
Ok, sometimes the "Constructor"-solution is sometimes hard to implement, depending of members.
Best regards
Detlev
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: how to create a copy of java object