Skip to main content

Posts

Showing posts from November, 2016

Java Cloning and Types of Cloning (Shallow and Deep) in Details with Example

In my previous article 5 Different ways to create objects in Java with Example , I have discussed 5 different ways (new keyword, Class.newInstance() method, Constructor.newInstance() method, clone() method and deserialization) a developer can use to create objects, if you haven't read it please go ahead. Cloning is also a way of creating an object but in general, cloning is not just about creating a new object. Cloning means creating a new object from an already present object and copying all data of given object to that new object. In order to create a clone of an object we generally design our class in such way that Our class should implement Cloneable interface otherwise, JVM will throw CloneNotSupportedException if we will call clone() on our object. Cloneable interface is a marker interface which JVM uses to analyse whether this object is allowed for cloning or not. According to JVM if yourObject instanceof Cloneable then create a copy of the object otherwise throw ...