Saturday, March 28, 2015

Java Object cloning

Object cloning means creating a copy of original object with different reference.

Object cloning can be of two types - Shallow cloning and Deep cloning.

Shallow cloning :-

Java Object Class already have a clone method. By default this clone method do shallow cloning.

As per java docs

Object clone method 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:

1) x.clone() != x will be true
2) x.clone().getClass() == x.getClass() will be true, but these are not absolute requirements.
3) x.clone().equals(x) will be true, this is not an absolute requirement.