Use the Clonable interface when defining the class, create a clone function with return type Object
, this function shall throw CloneNotSupportedException
and shall return the clone :
public class YourClass implements Cloneable{
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
and when you create the object, use the clone function as follows :
YourClass obj = new YourClass();
YourClass objCopy = (YourClass) obj.clone();
Here is a reference you can benefit from.
EDIT
You can also use copy constructor which is a better approach than clone :
class YourClass {
private String dummy;
public YourClass (YourClass another) {
this.dummy = another.dummy;
}
}
Your call
YourClass class1 = new YourClass();
YourClass clone = new YourClass(class1);