Skip to main content

Posts

Showing posts from January, 2013

Deep Cloning In Java

I have already mentioned about cloning in my previous post and also the types of cloning in java i.e. 1. Shallow cloning and 2. Deep cloning We have already seen what is shallow cloning, how to use it and the example to demonstrate it in my previous post you can read about it here . In this post we will discuss about deep cloning in java. Deep cloning basically refers to creating an exact copy of an object that means if we have a object class Person() {  String name;  Address address; //rest of the code } class Address () {  String state;  String city; //rest of the code } Now if I create a deep clone of the object "Person" then it will also create a new object of the "Address" and not a reference. Just to verify you can try making changes to the new "Address" object and then see if you still having the same value in the main object. That will be different if not then something is wrong. For creating a Deep clone you can use ei

Shallow cloning in Java

Cloning basically refers to creating an identical copy of an existing object.  The term  clone  is derived from  κλών , the Greek word for "twig, branch", referring to the process whereby a new plant can be created from a twig. The word 'Cloning' in java refers to the same meaning. When we say we have created a clone object in java we mean we have created a new object with identical values in the object. There are two type of cloning in java as below : 1. Shallow cloning 2. Deep cloning Since this article is about shallow cloning will give description about that only and will include about the deep cloning in my next post. Shallow cloning : So shallow cloning is nothing but creating a clone of the object but not in detail. Now what does that mean? It means that if you have a object with referenced object in your main object then shallow cloning will not clone them, it will just clone the attribute of the main object.  Let's take an example : I