Some serialization confusions........please help
confusion 1:
import java.io.*;
publicclass SerializeDog{
publicstaticvoid main(String[] args){
Collar c =new Collar(3);
Dog d =new Dog(c, 5);
System.out.println("before: collar size is "+ d.getCollar().getCollarSize());
try{
FileOutputStream fs =new FileOutputStream("testSer.ser");
ObjectOutputStream os =new ObjectOutputStream(fs);
os.writeObject(d);
os.close();
}catch (Exception e){ e.printStackTrace();}
try{
FileInputStream fis =new FileInputStream("testSer.ser");
ObjectInputStream ois =new ObjectInputStream(fis);
d = (Dog) ois.readObject();
ois.close();
}catch (Exception e){ e.printStackTrace();}
System.out.println("after: collar size is "+ d.getCollar().getCollarSize());
}
}
class Dogimplements Serializable{
private Collar theCollar;
privateint dogSize;
public Dog(Collar collar,int size){
theCollar = collar;
dogSize = size;
}
public Collar getCollar(){return theCollar;}
}
class Collarimplements Serializable{
privateint collarSize;
public Collar(int size){ collarSize = size;}
publicint getCollarSize(){return collarSize;}
}
//output is before 3,after 3
In the example above dog use instance variable of type collar which when is not serialized throws notserialized exception. So how do we serialize classes we don抰 have access to coding for e.g. if here we did抧t have access to collar class.
confusion 2:
import java.io.*;
class SuperNotSerial{
publicstaticvoid main(String [] args){
Dog d =new Dog(35,"Fido");
System.out.println("before: " + d.name +" "+ d.weight);
try{
FileOutputStream fs =new FileOutputStream("testSer.ser");
ObjectOutputStream os =new ObjectOutputStream(fs);
os.writeObject(d);
os.close();
}catch (Exception e){ e.printStackTrace();}
try{
FileInputStream fis =new FileInputStream("testSer.ser");
ObjectInputStream ois =new ObjectInputStream(fis);
d = (Dog) ois.readObject();
ois.close();
}catch (Exception e){ e.printStackTrace();}
System.out.println("after: " + d.name +" "
+ d.weight);
}
}
class Dogextends Animalimplements Serializable{
String name;
Dog(int w, String n){
weight = w;// inherited
name = n;// not inherited
}
}
class Animal{// not serializable !
int weight = 42;
}
//output
before: Fido 35
after: Fido 42
And in this example animal is not serialized so it takes default values when it desrialized for animal instance variable. So how the actual state of object gets saved at all?
Only the current serialized object has its state saved not its perant nor any other classes. So in actual programming wouldn抰 it become difficult to serialze and desiralize as even a simple program can have n type of objects not related by inheritance.

