This is one of the good and tricky interview question that ,if sub class implements Serializable interface then super class object can be Serialized or not ,the answer is No super class object can not serialized only sub class object can be serialized. Practical Example is that my father(parent) attributes or features can came in me(child), but my(child) attributes or features can not go into my father.
In below example we have implemented this concept practically ,here we have Animal class as parent class and Dog class as child class ,and Dog class is implementing serializable interface and extending the Animal class, in main method we have created Animal class Object ,and we are writing the object in file through ObjectOutputStream class, when we run this program it will throw java.io.NotSerializableException ,because Animal class has not implemented the serializable interface.
On the other hand, if parent class implements serializable interface then all the sub class can be serialized. Click here to see example.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; class Animal { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } } class Dog extends Animal implements Serializable { private static final long serialVersionUID = 1L; } public class Test { public static void main(String[] args) { try { Animal a = new Animal(); a.setName("MALAYALAM"); //Writing Object In File ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("D:/example.txt")); out.writeObject(a); out.flush(); out.close();
} catch (Exception e) { e.printStackTrace(); } } } |
Output :
Blog Author - Pushkar Khosla,
Software Developer by Profession with 3.0 Yrs of Experience , through this blog i'am sharing my industrial Java Knowledge to entire world. For any question or query any one can comment below or mail me at pushkar.itsitm52@gmail.com.
This blog is all about to learn Core Java ,Interview Programs and Coding tricks to polish your Java Knowledge. If you like the content of this blog please share this with your friends.
Software Developer by Profession with 3.0 Yrs of Experience , through this blog i'am sharing my industrial Java Knowledge to entire world. For any question or query any one can comment below or mail me at pushkar.itsitm52@gmail.com.
This blog is all about to learn Core Java ,Interview Programs and Coding tricks to polish your Java Knowledge. If you like the content of this blog please share this with your friends.
Java I/O Tutorial

No comments:
Post a Comment