I've been studying for the
SCJP exam recently and I came across the following question:
Given:
10. class Car implements Serializable { }
11.
12. class Ford extends Car { }
If you attempt to serialize an instance of Ford, what is the result?
a. Compilation fails.
b. One object is serialized.
c. Two objects are serialized.
d. An exception is thrown at runtime.
So, I went and created a program to resolve the question with the two classes; one extending from the other, adding in some code to output an instantiation of class 'Ford':
import java.io.Serializable;
import java.io.ObjectOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class Main
{
public static void main(
String [] args)
{
String filename = "c:\\test.ser";
if(args.length > 0)
{
filename = args[0];
}
Ford time = new Ford();
System.out.println(time.sCar);
FileOutputStream fos = null;
ObjectOutputStream out = null;
try
{
fos = new FileOutputStream(filename);
out = new ObjectOutputStream(fos);
out.writeObject(time);
out.close();
}
catch(IOException ex)
{
ex.printStackTrace();
}
}
}
class Car implements Serializable { private String sCar = "My Wonderful Car"; }
class Ford extends Car { public String sCar = "My Wonderful Ford"; }
Looking at the results of test.ser in a text editor, I can see both strings "My Wonderful Car" and "My Wonderful Ford" and also the names of the two classes - does this mean two objects are in the results of serialization (answer c) - or is it daft idea trying to make sense of a serialization in a text editor?