-2

I have a requirement where I need to generate Object from existed object. I am not able to select the which method is used either clone() or copy().

Situation is if user click the button say Copy/Clone I need to generate the new Employee object which is having existed Employee data.

Thanks in advance

kranthi
  • 55
  • 1
  • 10

1 Answers1

1

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);
KAD
  • 10,972
  • 4
  • 31
  • 73