sp00m
sp00m

Reputation: 48837

Why is java.io.Serializable not a class?

I understand this question can sound quite weird, but I wonder why the java.io.Serializable interface has been implemented precisely as an interface, and not as a class?

What made me think about that point, is that we're talking about overriding the readObject/writeObject methods, while by definition, we don't override them (i.e. there's no super type of our Serializable objects that already implement these methods).

Thus, if Serializable would have been a class, it could have implemented the default readObject/writeObject methods, and the exenting classes could then have been able to really override the said methods.


Here is a not working workaround that illustrates my words:

public class Serializable implements java.io.Serializable {

    private static final long serialVersionUID = 356223041512972356L;

    protected void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
        stream.defaultReadObject();
    }

    protected void writeObject(ObjectOutputStream stream) throws IOException {
        stream.defaultWriteObject();
    }

}

public class MyClass extends Serializable {

    private static final long serialVersionUID = -5437634103734137046L;

    @Override
    protected void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
        super.readObject(stream);
        // custom readObject method
    }

}

PS: the provided workaround doesn't work since the readObject/writeObject methods have to be declared as private while mine are protected.

Upvotes: 3

Views: 484

Answers (2)

Robert Munteanu
Robert Munteanu

Reputation: 68318

If java.io.Serializable would've been a class, you would've been unable to inherit from another base class.

To put it another way, it's either inheritance or serialization.

Upvotes: 4

djechlin
djechlin

Reputation: 60818

Because then you're really screwed if you want to inherit from another class and implement Serializable. This is the general trade-off Java made when choosing not to support true multiple inheritance.

You'll note that Java 2.0 languages (Groovy and Scala) reversed that decision via what they call traits or mixins - which are pretty much exactly designed so you can just "mix in" e.g. the Serializable functionality without logically just deriving from it - which you might take as evidence that you are making a very good point and Java would have done well to heed your opinion.

Upvotes: 12

Related Questions