Skip to content

Instantly share code, notes, and snippets.

@VijayKrishna
Created July 10, 2013 16:14
Show Gist options
  • Save VijayKrishna/5967668 to your computer and use it in GitHub Desktop.
Save VijayKrishna/5967668 to your computer and use it in GitHub Desktop.
This gist supports a question i answered on Stack overflow: http://stackoverflow.com/questions/17573955/confused-about-cloning-in-java
public class CloneTest implements Cloneable {
public static void main(String[] args) {
CloneTest original = new CloneTest("dummyname", new StringBuffer("Molly"), 1);
CloneTest clone = (CloneTest)original.clone();
System.out.println("orignal.name2:" + original.name2.toString());
System.out.println("clone.name2:" + clone.name2.toString());
clone.setName2("Dolly");
System.out.println("orignal.name2 (after clone update):" + original.name2.toString());
System.out.println("clone.name2: (after clone update):" + clone.name2.toString());
}
String name;
StringBuffer name2;
int marks;
public CloneTest(String s, StringBuffer s2, int i) {
name = s;
name2 = s2;
marks = i;
}
public void setName(String s) {
name = s;
}
public void setName2(String s) {
int length = this.name2.length();
this.name2.delete(0, length);
this.name2.append(s);
}
public void setMarks(int i) {
marks = i;
}
@Override
public Object clone() {
return new CloneTest(this.name, this.name2, this.marks);
}
}
orignal.name2:name2
clone.name2:name2
orignal.name2 (after clone update):Dolly
clone.name2: (after clone update):Dolly
[Finished in 0.1s]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment