Mars
Mars

Reputation: 4995

Extending a class that implements Serializable

If I extend a class that implements Serializable, do I need that class to also implement Serializable?

For instance if I have,

public class classToBeExtended implements Serializable

Then will this suffice?

public class classThatWillExtend extends classToExtended

Or do I need to do this?

public class classThatWillExtend extends classToExtended implements Serializable

Upvotes: 7

Views: 9946

Answers (2)

John Bollinger
John Bollinger

Reputation: 180181

If any of a class's superclasses implements a given interface, then the subclass also implements that interface. Serializable is not special in that regard, so no, the subclasses of a Serializable class do not need to explicitly declare that they implement Serializable. They can so declare, but doing that makes no difference.

The other implication is that if you extend a Serializable class, you should ensure that the subclass is indeed serializable itself. For example, don't add non-transient fields of non-serializable types unless you're prepared also to add the necessary methods to support them.

Upvotes: 6

tsolakp
tsolakp

Reputation: 5948

Per Javadoc:

All subtypes of a serializable class are themselves serializable

Upvotes: 3

Related Questions