Here we will discuss
Serializable
and for more details about
Externalizable
see
Externalizable In Java with Example.
Serializable
is a marker interface and so it does not have any methods. A class can be serialized if we simply implement this interface. For
e.g., the
Student
class below can be serialized since it implements
Serializable
interface.
class Student implements Serializable
{
String name;
int rollNumber;
char section;
}
Notice that there are no additional methods to be implemented.
We need to understand the following important points about
Serializable
.
- Any class which extends from Student will automatically be Serializable. For e.g., the
Engineer
class below is Serializable
since Student
implements Serializable
interface.
class Engineer extends Student
{
String branch;
}
- If a class contains objects of other classes, then those classes should also implement
Serializable
interface, otherwise the containing class can not be serialized. For e.g., Student
class contains Address
and if Address
does not implement Serializable
interface, then it throws a NotSerializableException
if we try to serialize an object of Student
class.
/*
// WON'T WORK SINCE NOT IMPLEMENTING Serializable INTERFACE
class Address
{
String doorNumber;
String line1;
}
*/
class Address implements Serializable
{
String doorNumber;
String line1;
}
class Student implements Serializable
{
String name;
int rollNumber;
char section;
Address address; // ANY CLASS INCLUDED SHOULD ALSO IMPLEMENT Serializable
}
- Any variables which are declared as
static
or transient
will not be serialized. Which means the value of those variables will be lost if we serialize and de-serialize. For e.g., below the values of allStudentsCount
and percentage
will be lost and they will set to their default values 0
and 0.0
after the serialization/de-serialization.
class Student implements Serializable
{
static int allStudentsCount; // WON'T BE SERIALIZED
String name;
int rollNumber;
char section;
transient double percentage; // WON'T BE SERIALIZED
}
Student.allStudentsCount = 25;
Student ravi = new Student();
ravi.name = "Ravi";
ravi.rollNumber = 35;
ravi.section = 'B';
ravi.percentage = 79.34;
// AFTER SERIALIZATION AND DESERIALIZATION THE VALUES OF allStudentsCount AND percentage WILL BE LOST
How exactly the serialization and deserialization is performed is explained in
Java Serialization Process -. Note that we can also implement serialization using
Externalizable In Java with Example interface.