What is object cloning in java with example
Object cloning in Java is the process of creating a duplicate copy of an object. Cloning is used to create an exact copy of an object, including its state. The
clone() method is used to perform object cloning in Java. It’s defined in the
Object class and is protected, which means you need to override it in your class to make it accessible from outside the class.
Here’s how you can implement object cloning in Java with an example:
In this example, the
Person class implements the
Cloneable interface, allowing objects of this class to be cloned. The
clone() method is overridden to provide a proper implementation of cloning.
Please note that
clone() method returns an
Object type, so you need to cast it to the appropriate type. Also, cloning can throw
CloneNotSupportedException if the class doesn’t implement
Keep in mind that the default
clone() method performs a shallow copy, meaning that it creates a new object but does not create copies of the objects referenced by the original object. If your class contains reference variables pointing to mutable objects, you might need to perform a deep copy to ensure that the cloned object is fully independent of the original one.