I have a class which implements Serializable. Now I extends this class and I want this extended class to be non Serializable. So how to do it?
For example. I have
You can't remove the interface, but you can prevent serialization at run-time:
class B extends A {
private void writeObject(ObjectOutputStream oos) throws IOException {
throw new NotSerializableException();
}
}
That's indeed not possible. Your best bet is to let B composite/decorate A.
public class B {
private A a = new A();
public void doSomething() {
a.doSomething();
}
}
Not possible. Liskov Substitution Principle and all.
As others have made clear, it's not possible for a subclass of a Serializable
class to be non-Serializable
.
If what you want is for the subclass' attributes not to be serialized, one option is to make them all transient.
If you need more than that (you don't want super class fields to be serialized), override writeObject(ObjectOutputStream)
and readObject(ObjectInputStream)
as outlined here - https://web.archive.org/web/20120626144013/http://java.sun.com/developer/technicalArticles/ALT/serialization
Answering one of your comment (and assuming you are talking of JPA or Hibernate):
But Any class which wants its object to be persisted should implement this. and I want my Class B's objects as non persistable.
If you don't want B to be persistent at all, don't mark it as @Entity
. But it doesn't really make sense for B to extend A if B is not a persistent entity IMHO. This would be a bad use of inheritance.
It will always be Serializable, though you could ensure nothing in the class ever gets serialized by making every member transient
.