• Post Reply Bookmark Topic Watch Topic
  • New Topic

Serialization Problem  RSS feed

 
nitin pokhriyal
Ranch Hand
Posts: 263
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi,
I wrote this code and it is compiling and running. Without java.io.NotSerializableException: error . I was expecting error as my Cat object created at line 4 is not serialized but when i replace line 4 with
Animal a=new Animal() which is superclass of Cat i am getting error
Why is it so? I am not getting any error when i am serializing Cat object
but when i try to serialize Animal object i am getting exception. Any suggestion.?



//package model;

//import java.io.*;
// 1
1.public class SerializeCat {
2.
3. public static void main(String[] args) {
4. Cat c = new Cat(); // 2
5. try {
6. FileOutputStream fs = new FileOutputStream("testSer.ser");
7. ObjectOutputStream os = new ObjectOutputStream(fs);
8. os.writeObject(c); // 3
9. os.close();
10. } catch (Exception e) {
11. e.printStackTrace();
12. }

13. try {
14. FileInputStream fis = new FileInputStream("testSer.ser");
15. ObjectInputStream ois = new ObjectInputStream(fis);
16. c = (Cat) ois.readObject(); // 4
17. ois.close();
18. } catch (Exception e) {
19. e.printStackTrace();
20. }
21. }
22.}
[ July 02, 2007: Message edited by: nitin pokhriyal ]
 
Biswajit Paria
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I was expecting error as my Cat object created at line 4 is not serialized but when i replace line 4 with
Animal a=new Animal() which is superclass of Cat i am getting error

if your Cat class is not Serializable, you will obviously get java.io.NotSerializableException exception....

The following senario where you would not get any exception:

1.If your Super class Animal implements Serializable interface then Cat class will not throw exception even it may not implement Serializable.

2.Your Super class does not implement Serializable and subclass Cat implements Serializable...then your above code will not throw exception...
 
Uday Bhaskar Kopalle
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi

The question is not so clear. you didnt included the Car and Animal class definitions in the code. In general, any class that wants to be serialized has to implement the Serializable Interface(The class itself or any one of its super classes). Otherwise this exception is thrown.

For more checkout examples on Serialization.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!