To create a copy of an object in Java, you can use the clone
method of the Object
class.
The clone
method is a protected method of the Object
class that creates a new object that is a copy of the original object. To use the clone
method, you must override it in the class of the object you want to copy and make it public. You can then call the clone
method on an instance of the object to create a copy of the object.
Here is an example of how you can override the clone
method and use it to create a copy of an object in Java:
public class MyObject implements Cloneable { private int value; public MyObject(int value) { this.value = value; } public int getValue() { return value; } public void setValue(int value) { this.value = value; } @Override public MyObject clone() throws CloneNotSupportedException { return (MyObject) super.clone(); } } MyObject obj1 = new MyObject(5); MyObject obj2 = obj1.clone();
This code defines a class called MyObject
that implements the Cloneable
interface. The Cloneable
interface is a marker interface that indicates that an object is eligible to be cloned. The MyObject
class overrides the clone
method of the Object
class and makes it public.
The clone
method of the Object
class creates a new object and copies the values of the fields of the original object to the new object. The clone
method returns the new object as an Object
, so you will need to cast it to the appropriate type. In this example, the clone
method returns the new object as a MyObject
.
To create a copy of an object, you can call the clone
method on an instance of the object. In this example, obj1
is an instance of MyObject class.
We use clone method to create another instance obj2.