Cloning an object in Java

I am trying to clone a DTO. I took the 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 gives me an 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 request is that the clone method is set to Object , so why can't we use it directly, how do we make the toString method?

+3
source share
3 answers

Actually, it doesn’t matter. You must override the clone method in your class from the moment it is protected in java.lang.Object. Remember to remove the CloneNotSupportedException in the method signature so you don't have to handle it everywhere in your code.

+1
source

You must override Object.clone (), which is protected. See java.lang.Cloneable and the documentation for Object.clone () .

A more complete example is here: How to implement the Cloneable interface .

+8
source

Unfortunately , Java cloning is broken . If you have an option, try defining your own clone interface that actually has the clone method or uses copy constructors to create copies of the object.

+4
source

Source: https://habr.com/ru/post/1485640/


All Articles