1.

How Can A Sub-class Of Serializable Super Class Avoid Serialization? If Serializable Interface Is Implemented By The Super Class Of A Class, How Can The Serialization Of The Class Be Avoided?

Answer»

In Java, if the super class of a class is IMPLEMENTING SERIALIZABLE interface, it means that it is already serializable. Since, an interface cannot be unimplemented, it is not possible to make a class non-serializable. However, the serialization of a new class can be avoided. For this, writeObject () and readObject() methods should be implemented in your class so that a Not Serializable Exception can be THROWN by these methods. And, this can be DONE by customizing the Java Serialization PROCESS. Below the code that demonstrates it

class MySubClass extends SomeSerializableSuperClass {

private void writeObject(java.io.ObjectOutputStream out)

throws IOException {

 throw new NotSerializableException(“Can not serialize this class”);

}

 private void readObject(java.io.ObjectInputStream in)

throws IOException, ClassNotFoundException {

 throw new NotSerializableException(“Can not serialize this class”);

}

private void readObjectNoData() 

throws ObjectStreamException; {

 throw new NotSerializableException(“Can not serialize this class”);

}

}

In Java, if the super class of a class is implementing Serializable interface, it means that it is already serializable. Since, an interface cannot be unimplemented, it is not possible to make a class non-serializable. However, the serialization of a new class can be avoided. For this, writeObject () and readObject() methods should be implemented in your class so that a Not Serializable Exception can be thrown by these methods. And, this can be done by customizing the Java Serialization process. Below the code that demonstrates it

class MySubClass extends SomeSerializableSuperClass {

private void writeObject(java.io.ObjectOutputStream out)

throws IOException {

 throw new NotSerializableException(“Can not serialize this class”);

}

 private void readObject(java.io.ObjectInputStream in)

throws IOException, ClassNotFoundException {

 throw new NotSerializableException(“Can not serialize this class”);

}

private void readObjectNoData() 

throws ObjectStreamException; {

 throw new NotSerializableException(“Can not serialize this class”);

}

}



Discussion

No Comment Found