Cloning objects in Java

I'm trying to clone dto I have photographed a dto object, as shown in the figure:

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 gave me a mistake:

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 the clone method is from object. Why can't we use it directly like the 'toString method?

Solution

Actually, it doesn't matter You need to override the clone method in the class because it is in Java Protected in lang.Object Don't forget to remove the clonenotsupportedexception from the method signature so you don't have to deal with it anywhere in the code

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>