Let's say we want to write an instance of Main to disk, having a name value of AA.
What is the value of name after this object has been read using the ObjectInputStream's readObject()
method?
package mypkg; // www . j av a 2 s. co m public class Main { private String name = "A"; private transient int sugar; public Main() { super(); this.name = "B"; } { name = "CC"; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getSugar() { return sugar; } public void setSugar(int sugar) { this.sugar = sugar; } }
D.
The Main class does not implement the Serializable interface; therefore, attempting to write the instance to disk, or calling readObject()
using ObjectInputStream, will result in a NotSerializableException at runtime.
Option D is the correct answer.
If the class did implement Serializable, then the value of name would be AA, since none of the constructor, initializers, or setters methods are used on deserialization, making Option B the correct answer.