do I need make some method like :
Pretty close. Instead of making it method, you should make it a constructor. Such constructors are called copy constructor, and you create them like this:
MyClass(MyClass data) {
a = data.a;
b = data.b;
}
And then to create copy of instance, you use the constructor like this:
MyClass obj1 = new MyClass();
MyClass obj2 = new MyClass(obj1);
Copy constructor can be tedious:
Using copy constructor to create deep-copy can be tedious, when your class has mutable fields. In which case, assignment like those will just create a copy of the reference, and not the object itself. You have to create copy of those fields also (If you want a deep copy). This can go recursive.
A better way to create deep copy is to Serialize and then Deserialize your object.
Why not use clone()?
Addition of clone()
method in Object class was a big mistake, IMO. You should avoid using it for cloning objects.
- For one, to use that method, you have to implement
Cloneable
interface, which by surprise doesn't actually have that clone()
method. In fact, it's just a marker interface.
- Return type of
Object#clone()
method is Object
. So, this means that you can actually return an instance of a completely unrelated class, thus leading your code to a potential ClassCastException
at runtime.
See also: