I am trying to clone a DTO. I have taken a DTO Object as shown:
public class Employee implements Cloneable
{
String name;
String dept;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDept() {
return dept;
}
public void setDept(String dept) {
this.dept = dept;
}
}
But this line is giving me Error :
public class Test
{
public static void main(String args[]) {
Employee emp1 = new Employee();
emp1.setDept("10");
emp1.setName("Kiran");
Employee emp2 = (Employee) emp1.clone(); // This Line is giving error .
}
}
My query is that clone method is from Object, so why can't we use it directly like we do the `toString Method?
You have to override Object.clone(), which is protected. See the java.lang.Cloneable and Object.clone() documentation.
More complete example here: How to implement Cloneable interface.
Unfortunately cloning in Java is broken. If you have an option, either try to define your own clone interface, one which actually has a clone method or use copy constructors to create copies of object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With