Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cloning an Object in Java

Tags:

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?


2 Answers

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.

like image 98
phtrivier Avatar answered Feb 27 '26 08:02

phtrivier


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.

like image 29
Sanjay T. Sharma Avatar answered Feb 27 '26 10:02

Sanjay T. Sharma



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!