I am not able to understand the basics of Serialization
in Java 1.6.
Below is the Dog
Class containing an instance variable of Collar
Class:
Dog.java
public class Dog implements Serializable {
private Collar collar;
public Collar getCollar() {
return collar;
}
public void setCollar(Collar collar) {
this.collar = collar;
}
}
The Collar class does not implements Serializable
interface as shown below:
Collar.java
public class Collar {
private int size;
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
}
Now when I try to serialize the Dog
then why it does not throw an NotSerializableException
? According to the contract the entire object graph should implement Serializable
but my Collar
class does not fulfill that.
Below is the main method for this demo:
public static void main(String[] args) {
try {
FileOutputStream fs = new FileOutputStream("E:\\test.ser");
ObjectOutputStream os = new ObjectOutputStream(fs);
Dog dog = new Dog();
// No exception thrown here, WHY?
// test.ser file is getting created properly.
os.writeObject(dog);
FileInputStream fis = new FileInputStream("E:\\test.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
Dog dog1 = (Dog)ois.readObject();
// Here I am getting a null Collar object
Collar c1 = dog1.getCollar();
Kindly explain this, I am totally confused while trying to implement all the theoretical stuffs :(
Could be because your dog
doesn't have a collar
!
Try with
Dog dog = new Dog();
dog.setCollar(new Collar());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With