tags:

views:

137

answers:

5

Serialization is a mechanism of storing the state of an object. Based on this definition we can say that the instance variables in an object can be serialized. Methods are behaviors of the class.

We can set and get the state of an object using the methods. So the methods are related to the instance variables of the class.

Then why can't we serialize the methods in Java ?

+5  A: 

What do you plan on 'after' serializing the methods? The state of the object has to be by definition should be its members and their behaviors would not come into picture. And serialization is saving the state of the object and not its behaviors.

Bragboy
When you have a polymorphic object, doesn't its type qualify as state ?
Alexandre C.
@Alexandre : What do you mean by polymorphic object ?
Bragboy
ok in java everything is polymorphic. I mean objects implementing a particular interface possibly differently. The way they implement the interface could be serialized.
Alexandre C.
In Java, everything is not polymorphic..
Bragboy
A: 

Methods are always serialized: as bytecode in a class file. There is no practical need to serialize them again.

Andreas_D
A: 

Because method the same for all instances of class, they only driven by its data. If you have class definition in your app - you have it's methods.

But data can change from instance to instance.

Vitaliy
A: 

A method per say does not have any state, and a serialized method call cannot be used for anything. On the other hand, a serialized thread is conceptually a snapshot or checkpoint of a computation, and that would be useful.

However, threads are not serializable in Java, and it would be really difficult to implement this. (For example, how would you cope with the case where the code of one of the active methods was changed between serializing and deserializing a thread?)

Stephen C
+1  A: 

From OOP perspective, the state of an object is the total state of its non-static fields. Methods are a way to define the object behaviour and are common to all instances (objects) of that class, so they are defined as fields at the Class object not as a field of the object (instance) itself. So serializing the object would store its state thus only its fields, but if you serialize the Class object of your objects you would be serializing the methods of those objects (thought I see no reason why would someone bother himself to do so).

LmSNe