Why I don't have there NotSerializableException
cause in class A
that is serialized I have private B b
that is not serialized and I know that if class implement Serializable
all composite classes have to implement Serializable
/Externalizable
as well.
import java.io.*;
public class Test
{
public static void main(String[] args) throws IOException
{
FileOutputStream fileOutput = new FileOutputStream("a.dat");
ObjectOutputStream outputStream = new ObjectOutputStream(fileOutput);
outputStream.writeObject(new A());
fileOutput.close();
outputStream.close();
}
}
class A implements Serializable
{
private int age;
private B b;
}
class B
{
}
When you serialise new A()
, b
is null
so no B
.
It is the runtime type that is important - for instance you could have class BDerived extends B implements java.ui.Serializable
. Or an ArrayList
could be serialised from List
field reference.
You can see the exception if you initialise b
with a non-null
, non-serialisable type. For instance
private B b = new B();