Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Implement Clone and Copy method inside a Class?

I have class called Employee with 3 property called ID,Name,Dept. I need to implement the Copy and Clone method? When I am using Copy or Clone method I need to avoid Casting? how will I do that?.

example: same as DataTable which is having DataTable.Copy() and DataTable.Clone().

like image 315
Kishore Kumar Avatar asked Nov 11 '10 08:11

Kishore Kumar


People also ask

How do you implement a clone method in java?

Creating a copy using the clone() methodThe class whose object's copy is to be made must have a public clone method in it or in one of its parent class. Every class that implements clone() should call super. clone() to obtain the cloned object reference. The class must also implement java.

Which class is used if we want to implement the clone () method?

The clone() method of Object class is used to clone an object. The java. lang. Cloneable interface must be implemented by the class whose object clone we want to create.

Can we directly call clone () method on the object of some class?

clone() is protected soo outside to java. lang package we can access this method in subclass directly or with subclass Object only. clone must not be called on non-cloneable objects, therefore it is not made public.

Which class contains clone method in java?

Java provides an assignment operator to copy the values but no operator to copy the object. Object class has a clone method which can be used to copy the values of an object without any side-effect.


1 Answers

You need to implement IClonable interface and provide implementation for the clone method. Don't implement this if you want to avoid casting.

A simple deep cloning method could be to serialize the object to memory and then deserialize it. All the custom data types used in your class need to be serializable using the [Serializable] attribute. For clone you can use something like

  public MyClass Clone()
    {
        MemoryStream ms = new MemoryStream();
        BinaryFormatter bf = new BinaryFormatter();

        bf.Serialize(ms, this);

        ms.Position = 0;
        object obj = bf.Deserialize(ms);
        ms.Close();

        return obj as MyClass;
    }

If your class only has value types, then you can use a copy constructor or just assign the values to a new object in the Clone method.

like image 87
Midhat Avatar answered Sep 19 '22 03:09

Midhat