public class Foo implements java.io.Serializable {
private int v1;
private static double v2;
private Loan v3 = new Loan();
}
Options:
A. An instance of Foo can be serialized because Foo implements Serializable.
B. An instance of Foo cannot be serialized because Foo contains a non-serializable instance variable v3.
C. If you mark v3 as transient, an instance of Foo is serializable.
D. b and c
Answer: D
Explanation: An object may not be serialized even though its class implements java.io.Serializable, because it may contain non-serializable instance variables.
Now my question is:
As far as I know, transient is used to turn off serialization. Then how is transient in this case, helping us to serialize foo?
transientdoesn’t disable serialization altogether; it just marks members that won’t be serialized. It’s typically used for stuff that would be incorrect or irrelevant when the object is unserialized, or stuff that it’d be less-than-safe to store (passwords, decrypted data, that sort of thing), or non-serializable stuff that could be easily reconstructed.In this case, i assume the
Loanclass isn’t serializable. (If it were, then A would be correct.) Markingv3as transient just tells Java not to worry about that field, but go ahead and serialize the others. This means an unserializedFoomight have a nullv3. If you want to store theLoanas well, you’d need to either keep track of enough info to recreate it at will, or change classLoanso that it implementsjava.io.Serializableas well.Alternatively, there are methods you could implement (
writeObject,readObject) if you need control over serialization. But that can be a bit of a hassle.