user663724
user663724

Reputation:

Cloning an Object in Java

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?

Upvotes: 3

Views: 3979

Answers (3)

phtrivier
phtrivier

Reputation: 13415

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.

Upvotes: 8

Sanjay T. Sharma
Sanjay T. Sharma

Reputation: 23248

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.

Upvotes: 4

Perception
Perception

Reputation: 80633

Actually, never mind. You need to override the clone method in your class since its protected in java.lang.Object. Don't forget to remove the CloneNotSupportedException in the method signature, so that you don't have to handle it everywhere in your code.

Upvotes: 1

Related Questions