import java.io.*;
import java.util.*;
public class Employee implements Cloneable,Serializable
{
int eno;
String ename;
Address addr;
public Employee(int en,String name,Address a)
{
eno=en;
ename=name;
addr=a;
}
public Object clone() throws CloneNotSupportedException
{
Object o=null;
try{
ByteArrayOutputStream baos=new ByteArrayOutputStream();
ObjectOutputStream oos=new ObjectOutputStream(baos);
oos.writeObject(this);
ByteArrayInputStream bais=new ByteArrayInputStream(baos.toByteArray());
ObjectInputStream ois=new ObjectInputStream(bais);
o=ois.readObject();
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
return o;
}
}
Address.java
import java.io.*;
import java.util.*;
public class Address implements Cloneable,Serializable
{
String streetno;
String city;
public Address(String s,String c)
{
streetno=s;
city=c;
}
}
Test.java
public class Test
{
public static void main(String[] args)
{
try
{
Address a1=new Address("123","Hyderabad");
Employee e1=new Employee(1,"Neil",a1);
Employee e2=(Employee)e1.clone();
System.out.println(e2.addr.city);
e1.addr.city="Mumbai";
e1.ename="shan";
System.out.println(e2.addr.city);
System.out.println(e2.ename);
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}
No comments:
Post a Comment