Hi,
I am Muthi. I was learning about serialization and came across this code.
import java.io.*;
class Collar {
private int collarSize;
public Collar(int size) {
collarSize = size;
}
public int getCollarSize() {
return collarSize;
}
public void setCollarSize(int size) {
collarSize = size;
}
}
class Dog implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private transient Collar theCollar;
private int dogSize;
public Dog(Collar c, int size) {
theCollar = c;
dogSize = size;
}
private void writeObject(ObjectOutputStream oos) throws Exception {
try {
oos.defaultWriteObject();
oos.writeInt(theCollar.getCollarSize());
oos.close();
} catch (Exception e) {
//e.printStackTrace();
}
}
private void readObject(ObjectInputStream ois) throws Exception {
try {
ois.defaultReadObject();
theCollar = new Collar(ois.readInt());
ois.close();
} catch (Exception e) {
//e.printStackTrace();
}
}
public Collar getCollar() {
return theCollar;
}
public int getDogSize() {
return dogSize;
}
public void setDogSize(int size) {
dogSize = size;
}
}
public class serializeDog {
public static void main(
String[] args) {
Collar c = new Collar(6);
Dog d = new Dog(c, 7);
System.out.println("** Dog Size :" + d.getDogSize() + ", Collar Size :"
+ c.getCollarSize());
try {
FileOutputStream bbb = new FileOutputStream("objects.txt");
ObjectOutputStream oos = new ObjectOutputStream(bbb);
oos.writeObject(d);
//oos.close();
} catch (Exception ex) {
//ex.printStackTrace();
}
d.setDogSize(23);
c.setCollarSize(99);
System.out.println("Serialization Done!");
System.out.println("Dog " + d.getDogSize() + ", collar :"
+ c.getCollarSize());
try {
FileInputStream aaa = new FileInputStream("objects.txt");
ObjectInputStream ois = new ObjectInputStream(aaa);
d = (Dog) ois.readObject();
//ois.close();
} catch (Exception ex) {
//ex.printStackTrace();
}
System.out.println("deSerialization Done!");
System.out.println("**** Dog Size :" + d.getDogSize()
+ ", Collar Size :" + d.getCollar().getCollarSize());
}
}
OUTPUT:
** Dog Size :7, Collar Size :6
Serialization Done!
Dog 23, collar :99
deSerialization Done!
**** Dog Size :23, Collar Size :99
As you can see in the code initially the collar size is 6 and dog size is 7 follwing which serialization is done. The values of collar size and dog size are then changed to 99 and 23 respectively. After the values are changed, deserialization is being done. When you look at the output you see the values of collar size and dog size are 99 and 23 but when the object was serialized it contained values 6 and 7. How and why is this happening?