• We create exact copy of the object using Cloneable in java.
  • We need to override object class clone() method.
  • This is also called clone of the object.
  • So we can create copy of object using two different way
    1. Shallow copy
    2. Depp copy




Shallow copy / Shallow cloning in java

  • In Shallow copy object reference will be copied instead of copying whole data of the object.
  • So the newly created object will be another reference for existing with same data means shallow copy of the object.
  • Whenever we change data in the original object same changes made to new object also because both are pointing to same object.

shallow copy in java


Program #1: Java example program to demonstrate shallow copy / shallow cloning



Example:
  1. package com.shallowcopyvsdeppcopy;

  2. public class Example{
  3. int a;
  4. int b;

  5. Example(int a, int b){
  6.     this.a=a;
  7.     this.b=b;
  8. }

  9. }


Empclone :

  1. package com.shallowcopyvsdeppcopy;

  2. public class Empclone implements Cloneable {

  3.     Example e;
  4.     int a;
  5.    
  6.     Empclone (int a, Example es){
  7.         this.a=a;
  8.         this.e=e;
  9.       
  10.     }
  11.    
  12.  public Object clone()throws CloneNotSupportedException{
  13.       
  14.         return super.clone();
  15.  }
  16.           
  17.    
  18. public static void main(String[] args) {
  19.     
  20.         Empclone a= new Empclone (2, new Example(3,3));
  21.         Empclone b=null;
  22.    
  23.         try {
  24.              b=(Empclone )a.clone();
  25.           
  26.         } catch (CloneNotSupportedException e) {
  27.             
  28.             e.printStackTrace();
  29.         }
  30.         System.out.println(a.e.a);
  31.         System.out.println(b.e.a);
  32.       
  33.         a.e.a=12;
  34.         System.out.println(a.e.a);
  35.         System.out.println(b.e.a);
  36.     }

  37. }

Output:


  1. 3
  2. 3
  3. 12
  4. 12

Instance Of Java

We will help you in learning.Please leave your comments and suggestions in comment section. if you any doubts please use search box provided right side. Search there for answers thank you.
«
Next
Newer Post
»
Previous
Older Post

No comments

Leave a Reply

Select Menu