Skip to main content

Posts

Showing posts with the label deep cloning

Object cloning in Java with example

In this post, we will discuss following items. What is object cloning in Java? How to implement cloning in Java? What is Cloneable interface and its main flaw? Shallow Cloning. Deep Cloning. Alternate to Cloning. What is object cloning in Java? Object cloning is the process of creating exact copy of that object. To do this, there are two pre-requisite in Java: 1) implement Cloneable interface 2) and, override the clone() defined in java.lang.Object class. The clone() is defined in java.lang.Object class and have protected access by default. You need to set its visibility to public by overriding it, so that you will be able to call this method from outside the class overriding it. General contract of clone() Creates and returns a copy of this object. The precise meaning of "copy" may depend on the class of the object. The general intent is that, for any object x, the expression: x.clone() != x will be true, and that the expression x.clone().getClass()