Skip to content

Instantly share code, notes, and snippets.

@MykolaBova
Last active August 29, 2015 14:06
Show Gist options
  • Save MykolaBova/9d7eaec24c4661742963 to your computer and use it in GitHub Desktop.
Save MykolaBova/9d7eaec24c4661742963 to your computer and use it in GitHub Desktop.
Clone complex object
import java.util.Date;
public class ClonePerson2 implements Cloneable{
private String name;
private Date dob;
public ClonePerson2(String name, Date dob) {
this.name = name;
this.dob = dob;
}
public String getName() {
return name;
}
public Date getDob() {
return dob;
}
public ClonePerson2 clone() {
ClonePerson2 p;
try {
p = (ClonePerson2) super.clone();
p.dob = (Date) dob.clone();
return p;
} catch (CloneNotSupportedException e) {
e.printStackTrace();
throw new RuntimeException();
}
}
public static void main(String[] args) {
ClonePerson2 p = new ClonePerson2("Sam", new Date());
System.out.println(p.getName());
System.out.println(p.getDob());
try {
Thread.sleep(2000); //1000 milliseconds is one second.
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
ClonePerson2 pClone = p.clone();
System.out.println(pClone.getName());
System.out.println(pClone.getDob());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment