How to Prevent Child class from Serialization in Java

8 08 2014

We have parent class which is serializable, but child class we should not allow serializable. for this we can writeObject,readObject API’s throw NotSerializableException Exception in Child Class.

1) Parent Class

public class Parent implements Serializable {
private static final long serialVersionUID = 1L;
public String name;
public String address;

2) Child Class

public class Child extends Parent implements Serializable {

public Integer aadhar;
public Integer id;

private void writeObject(ObjectOutputStream out) throws IOException {
throw new NotSerializableException();

private Object readObject(ObjectInputStream in) throws IOException,
ClassNotFoundException {
throw new NotSerializableException();



3) Serialize Implementation Example 

public class SerializeEx {
public static void main(String[] args) {
Child e = new Child(); = “Siva”;
e.address = “Bangalore”;
e.aadhar = 11122333; = 101;
try {
FileOutputStream fileOut = new FileOutputStream(“child.ser”);
ObjectOutputStream out = new ObjectOutputStream(fileOut);
System.out.printf(“Serialized data is saved in child.ser”);
} catch (IOException i) {

4) Error:

Wile Running this program:

at com.ts.test.serli.Child.writeObject(
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at Source)
at Source)
at Source)
at Source)
at Source)
at com.ts.test.serli.SerializeEx.main(


%d bloggers like this: