Cloneobject
Cloneobject
import java.io.*;
class Test
{
int x, y;
Test()
{
x = 10;
y = 20;
}
}
class Main
{
public static void main(String[] args)
{
Test ob1 = new Test();
System.out.println(ob1.x + " " + ob1.y);
// Creating a new reference variable ob2
// pointing to same address as ob1
Test ob2 = ob1;
// Any change made in ob2 will be reflected
// in ob1
ob2.x = 100;
System.out.println(ob1.x+" "+ob1.y);
System.out.println(ob2.x+" "+ob2.y);
}
}
SHALLOW COPY:
import java.util.ArrayList;
// An object reference of this class is
// contained by Test2
class Test
{
int x, y;
}
// Contains a reference of Test and implements
// clone with shallow copy.
class Test2 implements Cloneable
{
int a;
int b;
Test c = new Test();
public Object clone() throws
CloneNotSupportedException
{
return super.clone();
}
}
Public class Main
{
public static void main(String args[]) throws CloneNotSupportedException
{
Test2 t1 = new Test2();
t1.a = 10;
t1.b = 20;
t1.c.x = 30;
t1.c.y = 40;
Test2 t2 = (Test2)t1.clone();
// Creating a copy of object t1 and passing
// it to t2
t2.a = 100;
// Change in primitive type of t2 will not
// be reflected in t1 field
t2.c.x = 300;
// Change in object type field will be
// reflected in both t2 and t1(shallow copy)
System.out.println(t1.a + " " + t1.b + " " +
t1.c.x + " " + t1.c.y);
System.out.println(t2.a + " " + t2.b + " " +
t2.c.x + " " + t2.c.y);
}
}
DEEP COPY
// using clone()
import java.util.ArrayList;
// contained by Test2
class Test
{
int x, y;
int a, b;
CloneNotSupportedException
Test2 t = (Test2)super.clone();
return t;
}
}
CloneNotSupportedException
t1.a = 10;
t1.b = 20;
t1.c.x = 30;
t1.c.y = 40;
Test2 t3 = (Test2)t1.clone();
t3.a = 100;
// be reflected in t1 field
t3.c.x = 300;
class Teacher {
String designation = "Teacher";
String collegeName = "sdlctraining";
void does(){
System.out.println("Teaching");
}
}