In order to use the clone method, your classes must implement the Cloneable interface.
Check the sample code below.
public class MyClass implements Cloneable {
private String text;
private int size;
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
public MyClass clone() throws CloneNotSupportedException{
return (MyClass)super.clone();
}
}
Cloning...
try{
MyClass myClass = new MyClass();
myClass.setSize(6);
myClass.setText("sample");
MyClass myClass2 = myClass.clone();
} catch(Exception e){
e.printStackTrace();
}
Make sure that you override the equals method properly for object comparison.