Given the following code to read and write instances of MyClass, which definition of class MyClass will persist only its variable model?
class ReadWriteObjects { public void write(MyClass ph, String fileName) throws Exception { ObjectOutputStream oos = new ObjectOutputStream( new FileOutputStream(fileName)); oos.writeObject(ph);//from w ww.j av a2 s . c o m oos.flush(); oos.close(); } public MyClass read(String fileName) throws Exception { ObjectInputStream ois = new ObjectInputStream( new FileInputStream(fileName)); MyClass ph = (MyClass)ois.readObject(); ois.close(); return ph; } }
a class MyClass implements Serializable { int sessionId; String model = "abc"; }//from w w w . ja v a 2s . c om b class MyClass { transient int sessionId; String model = "abc"; } c class MyClass implements Persistable { transient int sessionId; String model = "abc"; } d class MyClass implements Serializable { transient int sessionId; String model = "abc"; }
d
To persist instances of a class, the class must implement the Serializable interface.
Serializable is a marker interface; it doesn't define any methods.
Also, to prevent a field from persisting, define it as a transient variable.
Option (a) doesn't mark the field sessionId
as transient.
Option (b) doesn't implement either Serializable or Externalizable.
Option (c) implements the Persistable
interface, which doesn't exist.