Wednesday, 10 August 2016

If Super class implements Serializable interface, Then sub classes can be Serializable or not ?

Implementing Serializable interface in super class make all sub class Serializable by default.
Static data member are not serialized because static is the part of class not object.

class X implements Serializable{
}
class Y extends X {
}
class Z extends Y {
String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class SeriazableExample extends Z{
String address;
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public static void main(String[] args) throws FileNotFoundException, IOException,                                     ClassNotFoundException {

Z z= new Z();
z.setName("Pushkar Khosla");
SeriazableExample t = new SeriazableExample();
t.setAddress("Uttam Nagar");
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(new                                 File("D:/zzz.txt")));
out.writeObject(z);
out.writeObject(t);
out.flush();
out.close();
ObjectInputStream in = new ObjectInputStream(new FileInputStream(new                                           File("D:/zzz.txt")));

Z z1 = (Z)in.readObject();
System.out.println("::"+z1.getName());
SeriazableExample t1 =(SeriazableExample)in.readObject();
System.out.println("::"+t1.getAddress());
}
}

No comments:

Post a Comment