views:

396

answers:

8

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

         class A implements Serializable.

and i have

         class B extends A.

But I want class B to be Non Serializable.

+3  A: 

Not possible. Liskov Substitution Principle and all.

Michael Borgwardt
A: 

You can't do that.

Thomas Lötzer
A: 

Further, why would you want to? Serializable doesn't require you to implement any methods. It's a marker interface.

Jonathon
But Any class which wants its object to be persisted should implement this. and I want my Class B's objects as non persistable.
GK
@gurukulki Are you writing a library or simply coding an application? Your choices are: Don't subclass A, don't mark A as Serializable, or ignore the whole deal and document that your class shouldn't be serialized.
Jonathon
Actually Jonathon, I am not writing any application. I was discussing with my friend on this topic, so he said we can do this but how he too don't know, So wanted to get an answer here.
GK
+4  A: 

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();
    }
}
BalusC
+2  A: 

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 - http://java.sun.com/developer/technicalArticles/ALT/serialization/

Jack Leow
+2  A: 

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();
    }
}
finnw
This could cause lots of issues, when someone checks whether you implement Serializable and then expects you to actually be serializable.
Thomas Lötzer
This is recommended by Sun. See http://java.sun.com/developer/technicalArticles/ALT/serialization/ (paragraph titled "Other Pointers".)
finnw
+1  A: 

It will always be Serializable, though you could ensure nothing in the class ever gets serialized by making every member transient.

Cuga
A: 

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.

Pascal Thivent