Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serializable and transient

To make a class serializable we do the following:

class A implements Serializable {
    transient Object a;
}

And not this:

serializable class A {
   transient Object a;
}

Why, if we want to make a class serializable, do we implement a special interface. And if we want to exclude some fields we use the keyword transient? Why aren't special keywords used in both cases? I mean were there any reasons to make the same thing in different ways? I know, there is no such keyword as serializable but why wasn't it introduced instead of the special interface Serializable?

like image 464
andrii Avatar asked Dec 17 '09 16:12

andrii


2 Answers

Why isn't used some special keyword to mark classes as serializable too? Serializable interface looks like a magic numbers in code and not like the language feature.

I think you have to look at it the other way: language keywords exist mainly to support compile-time language constructs. Serialization is a runtime mechanism. Additionally, you don't want to have an extra keyword for everything, because you then can't use it as an identifier. A marker interface on the other hand is much less intrusive.

The question is thus: why do we need a language keyword to mark transient fields? And the answer is that there simply was no other way to mark specific fields at that time.

Nowadays, one would use annotations for this purpose in both cases (and for other things like the obscure strictfp keyword as well).

like image 61
Michael Borgwardt Avatar answered Nov 09 '22 23:11

Michael Borgwardt


Serializable is a marker interface (like Cloneable) that is used to set a flag for standard Java runtime library code that an object can be serialised according to the designer of that class.

The transient keyword can be used to specify that an attribute does not need to be serialised, for instance because it is a derived attribute.

See also this reply to a similar question on SO and this one about designing marker interfaces.

Update

Why marker interfaces and no keywords for things like serializable, cloneable, etc? My guess would be the possibility to consistently extend the Java runtime lib with new marker interfaces combined with too many keywords if behavioural aspects made it into the language.

The fact that class attributes cannot implement Interfaces and transient can be seen as a generic property of an attribute makes sense of introducing transient as a language keyword.

like image 40
rsp Avatar answered Nov 09 '22 23:11

rsp