- A class that needs to be serialized must implement marker interface Serializable.
- A class can extends a base class that doesn't implement Serializable .
- A class if contains or has-a relation with any of such instance variable that doesn't implement Serializable will throw runtime exception while serializing . [ ..java.io.NotSerializableException ..]
- If the base class doesn't implement Ser then in that case while deserializing object the constructor of base class is called again while the transient and static variables of object will be intialized to default and recent vale respectively .
Try running below example
import java.io.*;
class Player {
Player() { System.out.print("p"); }
}
public class CardPlayer extends Player implements Serializable{
// Player p =new Player (); this can be commented to check Has-A relation ship
CardPlayer() { System.out.print("c"); }
public static void main(String[] args) {
CardPlayer c1 = new CardPlayer();
try {
FileOutputStream fos = new FileOutputStream("play.txt");
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(c1);
os.close();
FileInputStream fis = new FileInputStream("play.txt");
ObjectInputStream is = new ObjectInputStream(fis);
CardPlayer c2 = (CardPlayer) is.readObject();
is.close();
} catch (Exception x ) { System.out.println("here ") ; x.printStackTrace();}
}
}
public static void main(String[] args) {
CardPlayer c1 = new CardPlayer();
try {
FileOutputStream fos = new FileOutputStream("play.txt");
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(c1);
os.close();
FileInputStream fis = new FileInputStream("play.txt");
ObjectInputStream is = new ObjectInputStream(fis);
CardPlayer c2 = (CardPlayer) is.readObject();
is.close();
} catch (Exception x ) { System.out.println("here ") ; x.printStackTrace();}
}
}