instanceof java
Posts: 576
Nickname: instanceof
Registered: Jan, 2015
instanceof java is a java related one.
shallow copy java example program
Posted: Aug 14, 2016 1:49 AM
This post originated from an RSS feed registered with Java Buzz
by instanceof java.
Original Post: shallow copy java example program
Feed Title: Instance Of Java
Feed URL: http://feeds.feedburner.com/blogspot/TXghwE
Feed Description: Instance of Java. A place where you can learn java in simple way each and every topic covered with many points and sample programs.
Latest Java Buzz Posts
Latest Java Buzz Posts by instanceof java
Latest Posts From Instance Of Java
Advertisement
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:
Read: shallow copy java example program