File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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

how to create a copy of java object

Jignesh Patel

Joined: Jul 13, 2001
Posts: 6
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??
Kaspar Dahlqvist
Ranch Hand

Joined: Jun 18, 2001
Posts: 128
Hi there, patel_o (?) !
This is one way:
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!
Frank Carver

Joined: Jan 07, 1999
Posts: 6920
The Java Ranch has thousands of visitors every week, many with surprisingly similar names. To avoid confusion we have a naming convention, described at . 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.

Read about me at ~ 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
I agree. Here's the link:
subject: how to create a copy of java object
jQuery in Action, 3rd edition