- 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
- Shallow copy
- 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.
Program #1: Java example program to demonstrate shallow copy / shallow cloning
Example:
- package com.shallowcopyvsdeppcopy;
- public class Example{
- int a;
- int b;
- Example(int a, int b){
- this.a=a;
- this.b=b;
- }
- }
Empclone :
- package com.shallowcopyvsdeppcopy;
- public class Empclone implements Cloneable {
- Example e;
- int a;
- Empclone (int a, Example es){
- this.a=a;
- this.e=e;
- }
- public Object clone()throws CloneNotSupportedException{
- return super.clone();
- }
- public static void main(String[] args) {
- Empclone a= new Empclone (2, new Example(3,3));
- Empclone b=null;
- try {
- b=(Empclone )a.clone();
- } catch (CloneNotSupportedException e) {
- e.printStackTrace();
- }
- System.out.println(a.e.a);
- System.out.println(b.e.a);
- a.e.a=12;
- System.out.println(a.e.a);
- System.out.println(b.e.a);
- }
- }
Output:
- 3
- 3
- 12
- 12
No comments